repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
mentrena/SyncKit
Example/Common/Company/CompanyPresenter.swift
1
8407
// // CompanyPresenter.swift // SyncKitCoreDataExample // // Created by Manuel Entrena on 21/06/2019. // Copyright © 2019 Manuel Entrena. All rights reserved. // import UIKit import CloudKit import SyncKit protocol CompanyPresenter: class { func viewDidLoad() func didTapSynchronize() func didTapInsert() func didSelectCompany(at indexPath: IndexPath) func delete(at indexPath: IndexPath) } class DefaultCompanyPresenter: NSObject, CompanyPresenter { weak var view: CompanyView? let interactor: CompanyInteractor let wireframe: CompanyWireframe let synchronizer: CloudKitSynchronizer? let canEdit: Bool let settingsManager: SettingsManager var companies: [[Company]] = [] { didSet { let showsSync = settingsManager.isSyncEnabled let companySections = companies.map { CompanySection(companies: $0.map { company in CompanyCellViewModel(name: company.name ?? "Nil name", isSharing: company.isSharing, isSharedWithMe: company.isShared, showShareStatus: showsSync, shareAction: { [weak self] in self?.share(company: company) }) }) } view?.companySections = companySections } } private var sharingCompany: Company? init(view: CompanyView, interactor: CompanyInteractor, wireframe: CompanyWireframe, synchronizer: CloudKitSynchronizer?, canEdit: Bool, settingsManager: SettingsManager) { self.view = view self.interactor = interactor self.wireframe = wireframe self.synchronizer = synchronizer self.canEdit = canEdit self.settingsManager = settingsManager super.init() } func viewDidLoad() { view?.canEdit = canEdit view?.showsSync = settingsManager.isSyncEnabled interactor.load() } func didTapSynchronize() { guard let synchronizer = synchronizer else { return } view?.showLoading(true) synchronizer.synchronize { [weak self](error) in guard let self = self else { return } self.view?.showLoading(false) if let error = error { self.handle(error) } else if let zoneID = synchronizer.modelAdapters.first?.recordZoneID, self.synchronizer?.database.databaseScope == CKDatabase.Scope.private { self.synchronizer?.subscribeForChanges(in: zoneID, completion: { (error) in if let error = error { debugPrint("Failed to subscribe: \(error.localizedDescription)") } else { debugPrint("Subscribed for notifications") } }) } } } func didTapInsert() { let alertController = UIAlertController(title: "New company", message: nil, preferredStyle: .alert) alertController.addTextField { (textField) in textField.placeholder = "Enter company name" } alertController.addAction(UIAlertAction(title: "Add", style: .default, handler: { [interactor](_) in interactor.insertCompany(name: alertController.textFields?.first?.text ?? "") })) view?.present(alertController, animated: true, completion: nil) } func didSelectCompany(at indexPath: IndexPath) { let company = companies[indexPath.section][indexPath.row] var canEdit = true if company.isShared { if let share = synchronizer?.share(for: interactor.modelObject(for: company)!) { canEdit = share.currentUserParticipant?.permission == .readWrite } else { canEdit = false } } wireframe.show(company: company, canEdit: canEdit) } func delete(at indexPath: IndexPath) { interactor.delete(company: companies[indexPath.section][indexPath.row]) } func share(company: Company) { guard let synchronizer = synchronizer else { return } sharingCompany = company synchronizer.synchronize { [weak self](error) in guard error == nil, let strongSelf = self, let company = strongSelf.sharingCompany, let modelObject = strongSelf.interactor.modelObject(for: company) else { return } let share = synchronizer.share(for: modelObject) let container = CKContainer(identifier: synchronizer.containerIdentifier) let sharingController: UICloudSharingController if let share = share { sharingController = UICloudSharingController(share: share, container: container) } else { sharingController = UICloudSharingController(preparationHandler: { (controller, completionHandler) in synchronizer.share(object: modelObject, publicPermission: .readOnly, participants: [], completion: { (share, error) in share?[CKShare.SystemFieldKey.title] = company.name completionHandler(share, container, error) }) }) } sharingController.availablePermissions = [.allowPublic, .allowReadOnly, .allowReadWrite] sharingController.delegate = self strongSelf.view?.present(sharingController, animated: true, completion: nil) } } } extension DefaultCompanyPresenter: CompanyInteractorDelegate { func didUpdateCompanies(_ companies: [[Company]]) { DispatchQueue.main.async { self.companies = companies } } } extension DefaultCompanyPresenter { func handle(_ error: Error) { if let nserror = error as NSError?, nserror.code == CKError.changeTokenExpired.rawValue { //handle let alertController = UIAlertController(title: "Error", message: "The app hasn't synced in too long and the CloudKit token isn't valid. Data must be synced from scratch. Syncing will be disabled now, you can enable it again in Settings", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in // reset SyncKit self.settingsManager.isSyncEnabled = false })) view?.present(alertController, animated: true, completion: nil) } else { let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) view?.present(alertController, animated: true, completion: nil) } } } extension DefaultCompanyPresenter: UICloudSharingControllerDelegate { func itemTitle(for csc: UICloudSharingController) -> String? { return sharingCompany?.name ?? "" } func cloudSharingController(_ csc: UICloudSharingController, failedToSaveShareWithError error: Error) { debugPrint("\(error.localizedDescription)") } func cloudSharingControllerDidSaveShare(_ csc: UICloudSharingController) { guard let synchronizer = synchronizer, let share = csc.share, let company = sharingCompany, let modelObject = interactor.modelObject(for: company) else { return } synchronizer.cloudSharingControllerDidSaveShare(share, for: modelObject) interactor.refreshObjects() } func cloudSharingControllerDidStopSharing(_ csc: UICloudSharingController) { guard let synchronizer = synchronizer, let company = sharingCompany, let modelObject = interactor.modelObject(for: company) else { return } synchronizer.cloudSharingControllerDidStopSharing(for: modelObject) interactor.refreshObjects() } }
mit
43c1575d28788c235152837ad89f0bea
40.820896
233
0.600999
5.476221
false
false
false
false
flathead/Flame
Flame/VectorMath.swift
1
34986
// // VectorMath.swift // VectorMath // // Version 0.1 // // Created by Nick Lockwood on 24/11/2014. // Copyright (c) 2014 Nick Lockwood. All rights reserved. // // Distributed under the permissive zlib License // Get the latest version from here: // // https://github.com/nicklockwood/VectorMath // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // import Foundation //MARK: Types typealias Scalar = Float struct Vector2 { var x: Scalar var y: Scalar } struct Vector3 { var x: Scalar var y: Scalar var z: Scalar } struct Vector4 { var x: Scalar var y: Scalar var z: Scalar var w: Scalar } struct Matrix3 { var m11: Scalar var m12: Scalar var m13: Scalar var m21: Scalar var m22: Scalar var m23: Scalar var m31: Scalar var m32: Scalar var m33: Scalar } struct Matrix4 { var m11: Scalar var m12: Scalar var m13: Scalar var m14: Scalar var m21: Scalar var m22: Scalar var m23: Scalar var m24: Scalar var m31: Scalar var m32: Scalar var m33: Scalar var m34: Scalar var m41: Scalar var m42: Scalar var m43: Scalar var m44: Scalar } struct Quaternion { var x: Scalar var y: Scalar var z: Scalar var w: Scalar } //MARK: Scalar extension Scalar { static let Pi = Scalar(M_PI) static let HalfPi = Scalar(M_PI_2) static let QuarterPi = Scalar(M_PI_4) static let TwoPi = Scalar(M_PI * 2) static let DegreesPerRadian = 180 / Pi static let RadiansPerDegree = Pi / 180 static let Epsilon: Scalar = 0.0001 } func ~=(lhs: Scalar, rhs: Scalar) -> Bool { return abs(lhs - rhs) < .Epsilon } //MARK: Vector2 extension Vector2: Equatable, Hashable { static let Zero = Vector2(0, 0) static let X = Vector2(1, 0) static let Y = Vector2(0, 1) var hashValue: Int { return x.hashValue &+ y.hashValue } var lengthSquared: Scalar { return x * x + y * y } var length: Scalar { return sqrt(lengthSquared) } var inverse: Vector2 { return -self } init(_ x: Scalar, _ y: Scalar) { self.init(x: x, y: y) } init(_ v: [Scalar]) { assert(v.count == 2, "array must contain 2 elements, contained \(v.count)") x = v[0] y = v[1] } func toArray() -> [Scalar] { return [x, y] } func dot(v: Vector2) -> Scalar { return x * v.x + y * v.y } func cross(v: Vector2) -> Scalar { return x * v.y - y * v.x } func normalized() -> Vector2 { let lengthSquared = self.lengthSquared if lengthSquared ~= 0 || lengthSquared ~= 1 { return self } return self / sqrt(lengthSquared) } func rotatedBy(radians: Scalar) -> Vector2 { let cs = cos(radians) let sn = sin(radians) return Vector2(x * cs - y * sn, x * sn + y * cs) } func rotatedBy(radians: Scalar, around pivot: Vector2) -> Vector2 { return (self - pivot).rotatedBy(radians) + pivot } func angleWith(v: Vector2) -> Scalar { if self == v { return 0 } let t1 = normalized() let t2 = v.normalized() let cross = t1.cross(t2) let dot = max(-1, min(1, t1.dot(t2))) return atan2(cross, dot) } func interpolatedWith(v: Vector2, t: Scalar) -> Vector2 { return self + (v - self) * t } } prefix func -(v: Vector2) -> Vector2 { return Vector2(-v.x, -v.y) } func +(lhs: Vector2, rhs: Vector2) -> Vector2 { return Vector2(lhs.x + rhs.x, lhs.y + rhs.y) } func -(lhs: Vector2, rhs: Vector2) -> Vector2 { return Vector2(lhs.x - rhs.x, lhs.y - rhs.y) } func *(lhs: Vector2, rhs: Vector2) -> Vector2 { return Vector2(lhs.x * rhs.x, lhs.y * rhs.y) } func *(lhs: Vector2, rhs: Scalar) -> Vector2 { return Vector2(lhs.x * rhs, lhs.y * rhs) } func *(lhs: Vector2, rhs: Matrix3) -> Vector2 { return Vector2( lhs.x * rhs.m11 + lhs.y * rhs.m21 + rhs.m31, lhs.x * rhs.m12 + lhs.y * rhs.m22 + rhs.m32 ) } func /(lhs: Vector2, rhs: Vector2) -> Vector2 { return Vector2(lhs.x / rhs.x, lhs.y / rhs.y) } func /(lhs: Vector2, rhs: Scalar) -> Vector2 { return Vector2(lhs.x / rhs, lhs.y / rhs) } func ==(lhs: Vector2, rhs: Vector2) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } func ~=(lhs: Vector2, rhs: Vector2) -> Bool { return lhs.x ~= rhs.x && lhs.y ~= rhs.y } //MARK: Vector3 extension Vector3: Equatable, Hashable { static let Zero = Vector3(0, 0, 0) static let X = Vector3(1, 0, 0) static let Y = Vector3(0, 1, 0) static let Z = Vector3(0, 0, 1) var hashValue: Int { return x.hashValue &+ y.hashValue &+ z.hashValue } var lengthSquared: Scalar { return x * x + y * y + z * z } var length: Scalar { return sqrt(lengthSquared) } var inverse: Vector3 { return -self } var xy: Vector2 { get { return Vector2(x, y) } set (v) { x = v.x y = v.y } } var xz: Vector2 { get { return Vector2(x, z) } set (v) { x = v.x z = v.y } } var yz: Vector2 { get { return Vector2(y, z) } set (v) { y = v.x z = v.y } } init(_ x: Scalar, _ y: Scalar, _ z: Scalar) { self.init(x: x, y: y, z: z) } init(_ v: [Scalar]) { assert(v.count == 3, "array must contain 3 elements, contained \(v.count)") x = v[0] y = v[1] z = v[2] } func toArray() -> [Scalar] { return [x, y, z] } func dot(v: Vector3) -> Scalar { return x * v.x + y * v.y + z * v.z } func cross(v: Vector3) -> Vector3 { return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x) } func normalized() -> Vector3 { let lengthSquared = self.lengthSquared if lengthSquared ~= 0 || lengthSquared ~= 1 { return self } return self / sqrt(lengthSquared) } func interpolatedWith(v: Vector3, t: Scalar) -> Vector3 { return self + (v - self) * t } } prefix func -(v: Vector3) -> Vector3 { return Vector3(-v.x, -v.y, -v.z) } func +(lhs: Vector3, rhs: Vector3) -> Vector3 { return Vector3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z) } func -(lhs: Vector3, rhs: Vector3) -> Vector3 { return Vector3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z) } func *(lhs: Vector3, rhs: Vector3) -> Vector3 { return Vector3(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z) } func *(lhs: Vector3, rhs: Scalar) -> Vector3 { return Vector3(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs) } func *(lhs: Vector3, rhs: Matrix3) -> Vector3 { return Vector3( lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31, lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32, lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33 ) } func *(lhs: Vector3, rhs: Matrix4) -> Vector3 { return Vector3( lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31 + rhs.m41, lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32 + rhs.m42, lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33 + rhs.m43 ) } func *(v: Vector3, q: Quaternion) -> Vector3 { let qv = q.xyz let uv = qv.cross(v) let uuv = qv.cross(uv) return v + (uv * 2 * q.w) + (uuv * 2) } func /(lhs: Vector3, rhs: Vector3) -> Vector3 { return Vector3(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z) } func /(lhs: Vector3, rhs: Scalar) -> Vector3 { return Vector3(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs) } func ==(lhs: Vector3, rhs: Vector3) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z } func ~=(lhs: Vector3, rhs: Vector3) -> Bool { return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z } //MARK: Vector4 extension Vector4: Equatable, Hashable { static let Zero = Vector4(0, 0, 0, 0) static let X = Vector4(1, 0, 0, 0) static let Y = Vector4(0, 1, 0, 0) static let Z = Vector4(0, 0, 1, 0) static let W = Vector4(0, 0, 0, 1) var hashValue: Int { return x.hashValue &+ y.hashValue &+ z.hashValue &+ w.hashValue } var lengthSquared: Scalar { return x * x + y * y + z * z + w * w } var length: Scalar { return sqrt(lengthSquared) } var inverse: Vector4 { return -self } var xyz: Vector3 { get { return Vector3(x, y, z) } set (v) { x = v.x y = v.y z = v.z } } var xy: Vector2 { get { return Vector2(x, y) } set (v) { x = v.x y = v.y } } var xz: Vector2 { get { return Vector2(x, z) } set (v) { x = v.x z = v.y } } var yz: Vector2 { get { return Vector2(y, z) } set (v) { y = v.x z = v.y } } init(_ x: Scalar, _ y: Scalar, _ z: Scalar, _ w: Scalar) { self.init(x: x, y: y, z: z, w: w) } init(_ xyz: Vector3, _ w: Scalar) { self.init(x: xyz.x, y: xyz.y, z: xyz.z, w: w) } init(_ v: [Scalar]) { assert(v.count == 4, "array must contain 4 elements, contained \(v.count)") x = v[0] y = v[1] z = v[2] w = v[3] } func toArray() -> [Scalar] { return [x, y, z, w] } func dot(v: Vector4) -> Scalar { return x * v.x + y * v.y + z * v.z + w * v.w } func normalized() -> Vector4 { let lengthSquared = self.lengthSquared if lengthSquared ~= 0 || lengthSquared ~= 1 { return self } return self / sqrt(lengthSquared) } func interpolatedWith(v: Vector4, t: Scalar) -> Vector4 { return self + (v - self) * t } } prefix func -(v: Vector4) -> Vector4 { return Vector4(-v.x, -v.y, -v.z, -v.w) } func +(lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w) } func -(lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w) } func *(lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w) } func *(lhs: Vector4, rhs: Scalar) -> Vector4 { return Vector4(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs) } func *(lhs: Vector4, rhs: Matrix4) -> Vector4 { return Vector4( lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31 + lhs.w * rhs.m41, lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32 + lhs.w * rhs.m42, lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33 + lhs.w * rhs.m43, lhs.x * rhs.m14 + lhs.y * rhs.m24 + lhs.z * rhs.m34 + lhs.w * rhs.m44 ) } func /(lhs: Vector4, rhs: Vector4) -> Vector4 { return Vector4(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w) } func /(lhs: Vector4, rhs: Scalar) -> Vector4 { return Vector4(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs) } func ==(lhs: Vector4, rhs: Vector4) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w } func ~=(lhs: Vector4, rhs: Vector4) -> Bool { return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z && lhs.w ~= rhs.w } //MARK: Matrix3 extension Matrix3: Equatable, Hashable { static let Identity = Matrix3(1, 0 ,0 ,0, 1, 0, 0, 0, 1) var hashValue: Int { var hash = m11.hashValue &+ m12.hashValue &+ m13.hashValue hash = hash &+ m21.hashValue &+ m22.hashValue &+ m23.hashValue hash = hash &+ m31.hashValue &+ m32.hashValue &+ m33.hashValue return hash } init(_ m11: Scalar, _ m12: Scalar, _ m13: Scalar, _ m21: Scalar, _ m22: Scalar, _ m23: Scalar, _ m31: Scalar, _ m32: Scalar, _ m33: Scalar) { self.m11 = m11 // 0 self.m12 = m12 // 1 self.m13 = m13 // 2 self.m21 = m21 // 3 self.m22 = m22 // 4 self.m23 = m23 // 5 self.m31 = m31 // 6 self.m32 = m32 // 7 self.m33 = m33 // 8 } init(scale: Vector2) { self.init( scale.x, 0, 0, 0, scale.y, 0, 0, 0, 1 ) } init(translation: Vector2) { self.init( 1, 0, 0, 0, 1, 0, translation.x, translation.y, 1 ) } init(rotation radians: Scalar) { let cs = cos(radians) let sn = sin(radians) self.init( cs, sn, 0, -sn, cs, 0, 0, 0, 1 ) } init(_ m: [Scalar]) { assert(m.count == 9, "array must contain 9 elements, contained \(m.count)") self.init(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]) } func toArray() -> [Scalar] { return [m11, m12, m13, m21, m22, m23, m31, m32, m33] } var adjugate: Matrix3 { return Matrix3( m22 * m33 - m23 * m32, m13 * m32 - m12 * m33, m12 * m23 - m13 * m22, m23 * m31 - m21 * m33, m11 * m33 - m13 * m31, m13 * m21 - m11 * m23, m21 * m32 - m22 * m31, m12 * m31 - m11 * m32, m11 * m22 - m12 * m21 ) } var determinant: Scalar { return (m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32) - (m13 * m22 * m31 + m11 * m23 * m32 + m12 * m21 * m33) } var transpose: Matrix3 { return Matrix3(m11, m21, m31, m12, m22, m32, m13, m23, m33) } var inverse: Matrix3 { return adjugate * (1 / determinant) } func interpolatedWith(m: Matrix3, t: Scalar) -> Matrix3 { return Matrix3( m11 + (m.m11 - m11) * t, m12 + (m.m12 - m12) * t, m13 + (m.m13 - m13) * t, m21 + (m.m21 - m21) * t, m22 + (m.m22 - m22) * t, m23 + (m.m23 - m23) * t, m31 + (m.m31 - m31) * t, m32 + (m.m32 - m32) * t, m33 + (m.m33 - m33) * t ) } } prefix func -(m: Matrix3) -> Matrix3 { return m.inverse } func *(lhs: Matrix3, rhs: Matrix3) -> Matrix3 { return Matrix3( lhs.m11 * rhs.m11 + lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13, lhs.m12 * rhs.m11 + lhs.m22 * rhs.m12 + lhs.m32 * rhs.m13, lhs.m13 * rhs.m11 + lhs.m23 * rhs.m12 + lhs.m33 * rhs.m13, lhs.m11 * rhs.m21 + lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23, lhs.m12 * rhs.m21 + lhs.m22 * rhs.m22 + lhs.m32 * rhs.m23, lhs.m13 * rhs.m21 + lhs.m23 * rhs.m22 + lhs.m33 * rhs.m23, lhs.m11 * rhs.m31 + lhs.m21 * rhs.m32 + lhs.m31 * rhs.m33, lhs.m12 * rhs.m31 + lhs.m22 * rhs.m32 + lhs.m32 * rhs.m33, lhs.m13 * rhs.m31 + lhs.m23 * rhs.m32 + lhs.m33 * rhs.m33 ) } func *(lhs: Matrix3, rhs: Vector2) -> Vector2 { return rhs * lhs } func *(lhs: Matrix3, rhs: Vector3) -> Vector3 { return rhs * lhs } func *(lhs: Matrix3, rhs: Scalar) -> Matrix3 { return Matrix3( lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs, lhs.m21 * rhs, lhs.m22 * rhs, lhs.m23 * rhs, lhs.m31 * rhs, lhs.m32 * rhs, lhs.m33 * rhs ) } func ==(lhs: Matrix3, rhs: Matrix3) -> Bool { if lhs.m11 != rhs.m11 { return false } if lhs.m12 != rhs.m12 { return false } if lhs.m13 != rhs.m13 { return false } if lhs.m21 != rhs.m21 { return false } if lhs.m22 != rhs.m22 { return false } if lhs.m23 != rhs.m23 { return false } if lhs.m31 != rhs.m31 { return false } if lhs.m32 != rhs.m32 { return false } if lhs.m33 != rhs.m33 { return false } return true } func ~=(lhs: Matrix3, rhs: Matrix3) -> Bool { if !(lhs.m11 ~= rhs.m11) { return false } if !(lhs.m12 ~= rhs.m12) { return false } if !(lhs.m13 ~= rhs.m13) { return false } if !(lhs.m21 ~= rhs.m21) { return false } if !(lhs.m22 ~= rhs.m22) { return false } if !(lhs.m23 ~= rhs.m23) { return false } if !(lhs.m31 ~= rhs.m31) { return false } if !(lhs.m32 ~= rhs.m32) { return false } if !(lhs.m33 ~= rhs.m33) { return false } return true } //MARK: Matrix4 extension Matrix4: Equatable, Hashable { static let Identity = Matrix4(1, 0 ,0 ,0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) var hashValue: Int { var hash = m11.hashValue &+ m12.hashValue &+ m13.hashValue &+ m14.hashValue hash = hash &+ m21.hashValue &+ m22.hashValue &+ m23.hashValue &+ m24.hashValue hash = hash &+ m31.hashValue &+ m32.hashValue &+ m33.hashValue &+ m34.hashValue hash = hash &+ m41.hashValue &+ m42.hashValue &+ m43.hashValue &+ m44.hashValue return hash } init(_ m11: Scalar, _ m12: Scalar, _ m13: Scalar, _ m14: Scalar, _ m21: Scalar, _ m22: Scalar, _ m23: Scalar, _ m24: Scalar, _ m31: Scalar, _ m32: Scalar, _ m33: Scalar, _ m34: Scalar, _ m41: Scalar, _ m42: Scalar, _ m43: Scalar, _ m44: Scalar) { self.m11 = m11 // 0 self.m12 = m12 // 1 self.m13 = m13 // 2 self.m14 = m14 // 3 self.m21 = m21 // 4 self.m22 = m22 // 5 self.m23 = m23 // 6 self.m24 = m24 // 7 self.m31 = m31 // 8 self.m32 = m32 // 9 self.m33 = m33 // 10 self.m34 = m34 // 11 self.m41 = m41 // 12 self.m42 = m42 // 13 self.m43 = m43 // 14 self.m44 = m44 // 15 } init(scale s: Vector3) { self.init( s.x, 0, 0, 0, 0, s.y, 0, 0, 0, 0, s.z, 0, 0, 0, 0, 1 ) } init(translation t: Vector3) { self.init( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t.x, t.y, t.z, 1 ) } init(rotation axisAngle: Vector4) { self.init(quaternion: Quaternion(axisAngle: axisAngle)) } init(quaternion q: Quaternion) { self.init( 1 - 2 * (q.y * q.y + q.z * q.z), 2 * (q.x * q.y + q.z * q.w), 2 * (q.x * q.z - q.y * q.w), 0, 2 * (q.x * q.y - q.z * q.w), 1 - 2 * (q.x * q.x + q.z * q.z), 2 * (q.y * q.z + q.x * q.w), 0, 2 * (q.x * q.z + q.y * q.w), 2 * (q.y * q.z - q.x * q.w), 1 - 2 * (q.x * q.x + q.y * q.y), 0, 0, 0, 0, 1 ) } init(fovx: Scalar, fovy: Scalar, near: Scalar, far: Scalar) { self.init(fovy: fovy, aspect: fovx / fovy, near: near, far: far) } init(fovx: Scalar, aspect: Scalar, near: Scalar, far: Scalar) { self.init(fovy: fovx / aspect, aspect: aspect, near: near, far: far) } init(fovy: Scalar, aspect: Scalar, near: Scalar, far: Scalar) { let dz = far - near assert(dz > 0, "far value must be greater than near") assert(fovy > 0, "field of view must be nonzero and positive") assert(aspect > 0, "aspect ratio must be nonzero and positive") let r = fovy / 2 let cotangent = cos(r) / sin(r) self.init( cotangent / aspect, 0, 0, 0, 0, cotangent, 0, 0, 0, 0, -(far + near) / dz, -1, 0, 0, -2 * near * far / dz, 0 ) } init(top: Scalar, right: Scalar, bottom: Scalar, left: Scalar, near: Scalar, far: Scalar) { let dx = right - left let dy = top - bottom let dz = far - near self.init( 2 / dx, 0, 0, 0, 0, 2 / dy, 0, 0, 0, 0, -2 / dz, 0, -(right + left) / dx, -(top + bottom) / dy, -(far + near) / dz, 1 ) } init(_ m: [Scalar]) { assert(m.count == 16, "array must contain 16 elements, contained \(m.count)") m11 = m[0] m12 = m[1] m13 = m[2] m14 = m[3] m21 = m[4] m22 = m[5] m23 = m[6] m24 = m[7] m31 = m[8] m32 = m[9] m33 = m[10] m34 = m[11] m41 = m[12] m42 = m[13] m43 = m[14] m44 = m[15] } func toArray() -> [Scalar] { return [m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44] } var adjugate: Matrix4 { var m = Matrix4.Identity m.m11 = m22 * m33 * m44 - m22 * m34 * m43 m.m11 += -m32 * m23 * m44 + m32 * m24 * m43 m.m11 += m42 * m23 * m34 - m42 * m24 * m33 m.m21 = -m21 * m33 * m44 + m21 * m34 * m43 m.m21 += m31 * m23 * m44 - m31 * m24 * m43 m.m21 += -m41 * m23 * m34 + m41 * m24 * m33 m.m31 = m21 * m32 * m44 - m21 * m34 * m42 m.m31 += -m31 * m22 * m44 + m31 * m24 * m42 m.m31 += m41 * m22 * m34 - m41 * m24 * m32 m.m41 = -m21 * m32 * m43 + m21 * m33 * m42 m.m41 += m31 * m22 * m43 - m31 * m23 * m42 m.m41 += -m41 * m22 * m33 + m41 * m23 * m32 m.m12 = -m12 * m33 * m44 + m12 * m34 * m43 m.m12 += m32 * m13 * m44 - m32 * m14 * m43 m.m12 += -m42 * m13 * m34 + m42 * m14 * m33 m.m22 = m11 * m33 * m44 - m11 * m34 * m43 m.m22 += -m31 * m13 * m44 + m31 * m14 * m43 m.m22 += m41 * m13 * m34 - m41 * m14 * m33 m.m32 = -m11 * m32 * m44 + m11 * m34 * m42 m.m32 += m31 * m12 * m44 - m31 * m14 * m42 m.m32 += -m41 * m12 * m34 + m41 * m14 * m32 m.m42 = m11 * m32 * m43 - m11 * m33 * m42 m.m42 += -m31 * m12 * m43 + m31 * m13 * m42 m.m42 += m41 * m12 * m33 - m41 * m13 * m32 m.m13 = m12 * m23 * m44 - m12 * m24 * m43 m.m13 += -m22 * m13 * m44 + m22 * m14 * m43 m.m13 += m42 * m13 * m24 - m42 * m14 * m23 m.m23 = -m11 * m23 * m44 + m11 * m24 * m43 m.m23 += m21 * m13 * m44 - m21 * m14 * m43 m.m23 += -m41 * m13 * m24 + m41 * m14 * m23 m.m33 = m11 * m22 * m44 - m11 * m24 * m42 m.m33 += -m21 * m12 * m44 + m21 * m14 * m42 m.m33 += m41 * m12 * m24 - m41 * m14 * m22 m.m43 = -m11 * m22 * m43 + m11 * m23 * m42 m.m43 += m21 * m12 * m43 - m21 * m13 * m42 m.m43 += -m41 * m12 * m23 + m41 * m13 * m22 m.m14 = -m12 * m23 * m34 + m12 * m24 * m33 m.m14 += m22 * m13 * m34 - m22 * m14 * m33 m.m14 += -m32 * m13 * m24 + m32 * m14 * m23 m.m24 = m11 * m23 * m34 - m11 * m24 * m33 m.m24 += -m21 * m13 * m34 + m21 * m14 * m33 m.m24 += m31 * m13 * m24 - m31 * m14 * m23 m.m34 = -m11 * m22 * m34 + m11 * m24 * m32 m.m34 += m21 * m12 * m34 - m21 * m14 * m32 m.m34 += -m31 * m12 * m24 + m31 * m14 * m22 m.m44 = m11 * m22 * m33 - m11 * m23 * m32 m.m44 += -m21 * m12 * m33 + m21 * m13 * m32 m.m44 += m31 * m12 * m23 - m31 * m13 * m22 return m } private func determinantForAdjugate(m: Matrix4) -> Scalar { return m11 * m.m11 + m12 * m.m21 + m13 * m.m31 + m14 * m.m41 } var determinant: Scalar { return determinantForAdjugate(adjugate) } var transpose: Matrix4 { return Matrix4( m11, m21, m31, m41, m12, m22, m32, m42, m13, m23, m33, m43, m14, m24, m34, m44 ) } var inverse: Matrix4 { let adjugate = self.adjugate let determinant = determinantForAdjugate(adjugate) return adjugate * (1 / determinant) } } prefix func -(m: Matrix4) -> Matrix4 { return m.inverse } func *(lhs: Matrix4, rhs: Matrix4) -> Matrix4 { var m = Matrix4.Identity m.m11 = lhs.m11 * rhs.m11 + lhs.m21 * rhs.m12 m.m11 += lhs.m31 * rhs.m13 + lhs.m41 * rhs.m14 m.m12 = lhs.m12 * rhs.m11 + lhs.m22 * rhs.m12 m.m12 += lhs.m32 * rhs.m13 + lhs.m42 * rhs.m14 m.m13 = lhs.m13 * rhs.m11 + lhs.m23 * rhs.m12 m.m13 += lhs.m33 * rhs.m13 + lhs.m43 * rhs.m14 m.m14 = lhs.m14 * rhs.m11 + lhs.m24 * rhs.m12 m.m14 += lhs.m34 * rhs.m13 + lhs.m44 * rhs.m14 m.m21 = lhs.m11 * rhs.m21 + lhs.m21 * rhs.m22 m.m21 += lhs.m31 * rhs.m23 + lhs.m41 * rhs.m24 m.m22 = lhs.m12 * rhs.m21 + lhs.m22 * rhs.m22 m.m22 += lhs.m32 * rhs.m23 + lhs.m42 * rhs.m24 m.m23 = lhs.m13 * rhs.m21 + lhs.m23 * rhs.m22 m.m23 += lhs.m33 * rhs.m23 + lhs.m43 * rhs.m24 m.m24 = lhs.m14 * rhs.m21 + lhs.m24 * rhs.m22 m.m24 += lhs.m34 * rhs.m23 + lhs.m44 * rhs.m24 m.m31 = lhs.m11 * rhs.m31 + lhs.m21 * rhs.m32 m.m31 += lhs.m31 * rhs.m33 + lhs.m41 * rhs.m34 m.m32 = lhs.m12 * rhs.m31 + lhs.m22 * rhs.m32 m.m32 += lhs.m32 * rhs.m33 + lhs.m42 * rhs.m34 m.m33 = lhs.m13 * rhs.m31 + lhs.m23 * rhs.m32 m.m33 += lhs.m33 * rhs.m33 + lhs.m43 * rhs.m34 m.m34 = lhs.m14 * rhs.m31 + lhs.m24 * rhs.m32 m.m34 += lhs.m34 * rhs.m33 + lhs.m44 * rhs.m34 m.m41 = lhs.m11 * rhs.m41 + lhs.m21 * rhs.m42 m.m41 += lhs.m31 * rhs.m43 + lhs.m41 * rhs.m44 m.m42 = lhs.m12 * rhs.m41 + lhs.m22 * rhs.m42 m.m42 += lhs.m32 * rhs.m43 + lhs.m42 * rhs.m44 m.m43 = lhs.m13 * rhs.m41 + lhs.m23 * rhs.m42 m.m43 += lhs.m33 * rhs.m43 + lhs.m43 * rhs.m44 m.m44 = lhs.m14 * rhs.m41 + lhs.m24 * rhs.m42 m.m44 += lhs.m34 * rhs.m43 + lhs.m44 * rhs.m44 return m } func *(lhs: Matrix4, rhs: Vector3) -> Vector3 { return rhs * lhs } func *(lhs: Matrix4, rhs: Vector4) -> Vector4 { return rhs * lhs } func *(lhs: Matrix4, rhs: Scalar) -> Matrix4 { return Matrix4( lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs, lhs.m14 * rhs, lhs.m21 * rhs, lhs.m22 * rhs, lhs.m23 * rhs, lhs.m24 * rhs, lhs.m31 * rhs, lhs.m32 * rhs, lhs.m33 * rhs, lhs.m34 * rhs, lhs.m41 * rhs, lhs.m42 * rhs, lhs.m43 * rhs, lhs.m44 * rhs ) } func ==(lhs: Matrix4, rhs: Matrix4) -> Bool { if lhs.m11 != rhs.m11 { return false } if lhs.m12 != rhs.m12 { return false } if lhs.m13 != rhs.m13 { return false } if lhs.m14 != rhs.m14 { return false } if lhs.m21 != rhs.m21 { return false } if lhs.m22 != rhs.m22 { return false } if lhs.m23 != rhs.m23 { return false } if lhs.m24 != rhs.m24 { return false } if lhs.m31 != rhs.m31 { return false } if lhs.m32 != rhs.m32 { return false } if lhs.m33 != rhs.m33 { return false } if lhs.m34 != rhs.m34 { return false } if lhs.m41 != rhs.m41 { return false } if lhs.m42 != rhs.m42 { return false } if lhs.m43 != rhs.m43 { return false } if lhs.m44 != rhs.m44 { return false } return true } func ~=(lhs: Matrix4, rhs: Matrix4) -> Bool { if !(lhs.m11 ~= rhs.m11) { return false } if !(lhs.m12 ~= rhs.m12) { return false } if !(lhs.m13 ~= rhs.m13) { return false } if !(lhs.m14 ~= rhs.m14) { return false } if !(lhs.m21 ~= rhs.m21) { return false } if !(lhs.m22 ~= rhs.m22) { return false } if !(lhs.m23 ~= rhs.m23) { return false } if !(lhs.m24 ~= rhs.m24) { return false } if !(lhs.m31 ~= rhs.m31) { return false } if !(lhs.m32 ~= rhs.m32) { return false } if !(lhs.m33 ~= rhs.m33) { return false } if !(lhs.m34 ~= rhs.m34) { return false } if !(lhs.m41 ~= rhs.m41) { return false } if !(lhs.m42 ~= rhs.m42) { return false } if !(lhs.m43 ~= rhs.m43) { return false } if !(lhs.m44 ~= rhs.m44) { return false } return true } //MARK: Quaternion extension Quaternion: Equatable, Hashable { static let Zero = Quaternion(0, 0, 0, 0) static let Identity = Quaternion(0, 0, 0, 1) var hashValue: Int { return x.hashValue &+ y.hashValue &+ z.hashValue &+ w.hashValue } var lengthSquared: Scalar { return x * x + y * y + z * z + w * w } var length: Scalar { return sqrt(lengthSquared) } var inverse: Quaternion { return -self } var xyz: Vector3 { get { return Vector3(x, y, z) } set (v) { x = v.x y = v.y z = v.z } } var pitch: Scalar { return atan2(2 * (y * z + w * x), w * w - x * x - y * y + z * z) } var yaw: Scalar { return asin(-2 * (x * z - w * y)) } var roll: Scalar { return atan2(2 * (x * y + w * z), w * w + x * x - y * y - z * z) } init(_ x: Scalar, _ y: Scalar, _ z: Scalar, _ w: Scalar) { self.init(x: x, y: y, z: z, w: w) } init(axisAngle: Vector4) { let r = axisAngle.w * 0.5 let scale = sin(r) let a = axisAngle.xyz * scale self.init(a.x, a.y, a.z, cos(r)) } init(pitch: Scalar, yaw: Scalar, roll: Scalar) { let sy = sin(yaw * 0.5) let cy = cos(yaw * 0.5) let sz = sin(roll * 0.5) let cz = cos(roll * 0.5) let sx = sin(pitch * 0.5) let cx = cos(pitch * 0.5) self.init( cy * cz * cx - sy * sz * sx, sy * sz * cx + cy * cz * sx, sy * cz * cx + cy * sz * sx, cy * sz * cx - sy * cz * sx ) } init(rotationMatrix m: Matrix4) { let diagonal = m.m11 + m.m22 + m.m33 + 1 if diagonal ~= 0 { let scale = sqrt(diagonal) * 2 self.init( (m.m32 - m.m23) / scale, (m.m13 - m.m31) / scale, (m.m21 - m.m12) / scale, 0.25 * scale ) } else if m.m11 > max(m.m22, m.m33) { let scale = sqrt(1 + m.m11 - m.m22 - m.m33) * 2 self.init( 0.25 * scale, (m.m21 + m.m12) / scale, (m.m13 + m.m31) / scale, (m.m32 - m.m23) / scale ) } else if m.m22 > m.m33 { let scale = sqrt(1 + m.m22 - m.m11 - m.m33) * 2 self.init( (m.m21 + m.m12) / scale, 0.25 * scale, (m.m32 + m.m23) / scale, (m.m13 - m.m31) / scale ) } else { let scale = sqrt(1 + m.m33 - m.m11 - m.m22) * 2 self.init( (m.m13 + m.m31) / scale, (m.m32 + m.m23) / scale, 0.25 * scale, (m.m21 - m.m12) / scale ) } } init(_ v: [Scalar]) { assert(v.count == 4, "array must contain 4 elements, contained \(v.count)") x = v[0] y = v[1] z = v[2] w = v[3] } func toAxisAngle() -> Vector4 { let scale = xyz.length if scale ~= 0 || scale ~= .TwoPi { return .Z } else { return Vector4(x / scale, y / scale, z / scale, acos(w) * 2) } } func toPitchYawRoll() -> (pitch: Scalar, yaw: Scalar, roll: Scalar) { return (pitch, yaw, roll) } func toArray() -> [Scalar] { return [x, y, z, w] } func dot(v: Quaternion) -> Scalar { return x * v.x + y * v.y + z * v.z + w * v.w } func normalized() -> Quaternion { let lengthSquared = self.lengthSquared if lengthSquared ~= 0 || lengthSquared ~= 1 { return self } return self / sqrt(lengthSquared) } func interpolatedWith(q: Quaternion, t: Scalar) -> Quaternion { let dot = max(-1, min(1, self.dot(q))) if dot ~= 1 { return (self + (q - self) * t).normalized() } let theta = acos(dot) * t let t1 = self * cos(theta) let t2 = (q - (self * dot)).normalized() * sin(theta) return t1 + t2 } } prefix func -(q: Quaternion) -> Quaternion { return Quaternion(-q.x, -q.y, -q.z, q.w) } func +(lhs: Quaternion, rhs: Quaternion) -> Quaternion { return Quaternion(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w) } func -(lhs: Quaternion, rhs: Quaternion) -> Quaternion { return Quaternion(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w) } func *(lhs: Quaternion, rhs: Quaternion) -> Quaternion { return Quaternion( lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y, lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z, lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x, lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z ) } func *(lhs: Quaternion, rhs: Vector3) -> Vector3 { return rhs * lhs } func *(lhs: Quaternion, rhs: Scalar) -> Quaternion { return Quaternion(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs) } func /(lhs: Quaternion, rhs: Scalar) -> Quaternion { return Quaternion(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs) } func ==(lhs: Quaternion, rhs: Quaternion) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w } func ~=(lhs: Quaternion, rhs: Quaternion) -> Bool { return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z && lhs.w ~= rhs.w }
mit
c78eb8f6c03c2edf8259fd900e6a7f08
25.891622
105
0.482907
2.898832
false
false
false
false
qinting513/SwiftNote
youtube/YouTube/Model/Video.swift
1
3356
// // Video.swift // YouTube // // Created by Haik Aslanyan on 7/26/16. // Copyright © 2016 Haik Aslanyan. All rights reserved. // import Foundation import UIKit class Video { //MARK: Properties let videoLink: URL let title: String let viewCount: Int let likes: Int let disLikes: Int let channelTitle: String let channelPic: UIImage let channelSubscribers: Int var suggestedVideos = [SuggestedVideo]() //MARK: Inits init(videoLink: URL, title: String, viewCount: Int, likes: Int, disLikes: Int, channelTitle: String, channelPic: UIImage, channelSubscribers: Int, suggestedVideos: [SuggestedVideo]) { self.videoLink = videoLink self.title = title self.viewCount = viewCount self.likes = likes self.disLikes = disLikes self.channelTitle = channelTitle self.channelPic = channelPic self.channelSubscribers = channelSubscribers self.suggestedVideos = suggestedVideos } //MARK: Methods class func download(link: URL, completiotion: @escaping ((Video) -> Void)) { URLSession.shared.dataTask(with: link) { (data, _, error) in if error == nil { do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] let videoLink = URL.init(string: (json["videoLink"] as! String)) let title = json["title"] as! String let viewCount = json["viewCount"] as! Int let likes = json["likes"] as! Int let disLikes = json["disLikes"] as! Int let channelTitle = json["channelTitle"] as! String let channelPic = UIImage.contentOfURL(link: (json["channelPic"] as! String)) let channelSubscribers = json["channelSubscribers"] as! Int let suggestedVideosList = json["suggestedVideos"] as! [[String : String]] var suggestedVideos = [SuggestedVideo]() for item in suggestedVideosList { let videoTitle = item["title"]! let thumbnail = UIImage.contentOfURL(link: item["thumbnail_image_name"]!) let name = item["name"]! let suggestedItem = SuggestedVideo.init(title: videoTitle, name: name, thumbnail: thumbnail) suggestedVideos.append(suggestedItem) } let video = Video.init(videoLink: videoLink!, title: title, viewCount: viewCount, likes: likes, disLikes: disLikes, channelTitle: channelTitle, channelPic: channelPic, channelSubscribers: channelSubscribers, suggestedVideos: suggestedVideos) completiotion(video) } catch _ { showNotification() } } }.resume() } }
apache-2.0
99b58893eddbffca50d9e8643b0cc8cf
42.012821
187
0.518033
5.325397
false
false
false
false
KrishMunot/swift
stdlib/public/core/Process.swift
1
2823
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims internal class _Box<T> { var value = [String]() init(_ value : [String]) { self.value = value } } /// Command-line arguments for the current process. public enum Process { /// Return an array of string containing the list of command-line arguments /// with which the current process was invoked. internal static func _computeArguments() -> [String] { var result: [String] = [] for i in 0..<Int(argc) { let arg = unsafeArgv[i] result.append( arg == nil ? "" : String(cString: arg) ) } return result } @_versioned internal static var _argc: CInt = CInt() @_versioned internal static var _unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = nil /// Access to the raw argc value from C. public static var argc: CInt { return _argc } /// Access to the raw argv value from C. Accessing the argument vector /// through this pointer is unsafe. public static var unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>> { return _unsafeArgv } /// Access to the swift arguments, also use lazy initialization of static /// properties to safely initialize the swift arguments. /// /// NOTE: we can not use static lazy let initializer as they can be moved /// around by the optimizer which will break the data dependence on argc /// and argv. public static var arguments: [String] { let argumentsPtr = UnsafeMutablePointer<AnyObject?>( Builtin.addressof(&_swift_stdlib_ProcessArguments)) // Check whether argument has been initialized. if let arguments = _stdlib_atomicLoadARCRef(object: argumentsPtr) { return (arguments as! _Box<[String]>).value } let arguments = _Box<[String]>(_computeArguments()) _stdlib_atomicInitializeARCRef(object: argumentsPtr, desired: arguments) return arguments.value } } /// Intrinsic entry point invoked on entry to a standalone program's "main". @_transparent public // COMPILER_INTRINSIC func _stdlib_didEnterMain( argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>> ) { // Initialize the Process.argc and Process.unsafeArgv variables with the // values that were passed in to main. Process._argc = CInt(argc) Process._unsafeArgv = UnsafeMutablePointer(argv) }
apache-2.0
c44d62ca95081b302ad20b2f9902e940
31.448276
80
0.663124
4.567961
false
false
false
false
varkor/firefox-ios
Sync/KeyBundle.swift
1
10541
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import FxA import Account private let KeyLength = 32 public class KeyBundle: Hashable { let encKey: NSData let hmacKey: NSData public class func fromKB(kB: NSData) -> KeyBundle { let salt = NSData() let contextInfo = FxAClient10.KW("oldsync") let len: UInt = 64 // KeyLength + KeyLength, without type nonsense. let derived = kB.deriveHKDFSHA256KeyWithSalt(salt, contextInfo: contextInfo, length: len) return KeyBundle(encKey: derived.subdataWithRange(NSRange(location: 0, length: KeyLength)), hmacKey: derived.subdataWithRange(NSRange(location: KeyLength, length: KeyLength))) } public class func random() -> KeyBundle { // Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which // on iOS is populated by the OS from kernel-level sources of entropy. // That should mean that we don't need to seed or initialize anything before calling // this. That is probably not true on (some versions of) OS X. return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32)) } public class var invalid: KeyBundle { return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef") } public init(encKeyB64: String, hmacKeyB64: String) { self.encKey = Bytes.decodeBase64(encKeyB64) self.hmacKey = Bytes.decodeBase64(hmacKeyB64) } public init(encKey: NSData, hmacKey: NSData) { self.encKey = encKey self.hmacKey = hmacKey } private func _hmac(ciphertext: NSData) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) { let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256) let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CCHmac(hmacAlgorithm, hmacKey.bytes, hmacKey.length, ciphertext.bytes, ciphertext.length, result) return (result, digestLen) } public func hmac(ciphertext: NSData) -> NSData { let (result, digestLen) = _hmac(ciphertext) let data = NSMutableData(bytes: result, length: digestLen) result.destroy() return data } /** * Returns a hex string for the HMAC. */ public func hmacString(ciphertext: NSData) -> String { let (result, digestLen) = _hmac(ciphertext) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String(hash) } public func encrypt(cleartext: NSData, iv: NSData?=nil) -> (ciphertext: NSData, iv: NSData)? { let iv = iv ?? Bytes.generateRandomBytes(16) let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt)) if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = NSData(bytes: b, length: Int(copied)) b.destroy() return (d, iv) } b.destroy() return nil } // You *must* verify HMAC before calling this. public func decrypt(ciphertext: NSData, iv: NSData) -> String? { let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt)) if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = NSData(bytesNoCopy: b, length: Int(copied)) let s = NSString(data: d, encoding: NSUTF8StringEncoding) b.destroy() return s as String? } b.destroy() return nil } private func crypt(input: NSData, iv: NSData, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutablePointer<Void>, count: Int) { let resultSize = input.length + kCCBlockSizeAES128 let result = UnsafeMutablePointer<Void>.alloc(resultSize) var copied: Int = 0 let success: CCCryptorStatus = CCCrypt(op, CCHmacAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), encKey.bytes, kCCKeySizeAES256, iv.bytes, input.bytes, input.length, result, resultSize, &copied ) return (success, result, copied) } public func verify(hmac hmac: NSData, ciphertextB64: NSData) -> Bool { let expectedHMAC = hmac let computedHMAC = self.hmac(ciphertextB64) return expectedHMAC.isEqualToData(computedHMAC) } /** * Swift can't do functional factories. I would like to have one of the following * approaches be viable: * * 1. Derive the constructor from the consumer of the factory. * 2. Accept a type as input. * * Neither of these are viable, so we instead pass an explicit constructor closure. * * Most of these approaches produce either odd compiler errors, or -- worse -- * compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159). * * For this reason, be careful trying to simplify or improve this code. */ public func factory<T: CleartextPayloadJSON>(f: JSON -> T) -> String -> T? { return { (payload: String) -> T? in let potential = EncryptedJSON(json: payload, keyBundle: self) if !(potential.isValid()) { return nil } let cleartext = potential.cleartext if (cleartext == nil) { return nil } return f(cleartext!) } } // TODO: how much do we want to move this into EncryptedJSON? public func serializer<T: CleartextPayloadJSON>(f: T -> JSON) -> Record<T> -> JSON? { return { (record: Record<T>) -> JSON? in let json = f(record.payload) if let data = json.toString(false).utf8EncodedData, // We pass a null IV, which means "generate me a new one". // We then include the generated IV in the resulting record. let (ciphertext, iv) = self.encrypt(data, iv: nil) { // So we have the encrypted payload. Now let's build the envelope around it. let ciphertext = ciphertext.base64EncodedString // The HMAC is computed over the base64 string. As bytes. Yes, I know. if let encodedCiphertextBytes = ciphertext.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false) { let hmac = self.hmacString(encodedCiphertextBytes) let iv = iv.base64EncodedString // The payload is stringified JSON. Yes, I know. let payload = JSON([ "ciphertext": ciphertext, "IV": iv, "hmac": hmac, ]).toString(false) return JSON([ "id": record.id, "sortindex": record.sortindex, "ttl": record.ttl ?? JSON.null, "payload": payload, ]) } } return nil } } public func asPair() -> [String] { return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString] } public var hashValue: Int { return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue } } public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool { return lhs.encKey.isEqualToData(rhs.encKey) && lhs.hmacKey.isEqualToData(rhs.hmacKey) } public class Keys: Equatable { let valid: Bool let defaultBundle: KeyBundle var collectionKeys: [String: KeyBundle] = [String: KeyBundle]() public init(defaultBundle: KeyBundle) { self.defaultBundle = defaultBundle self.valid = true } public init(payload: KeysPayload?) { if let payload = payload where payload.isValid() { if let keys = payload.defaultKeys { self.defaultBundle = keys self.collectionKeys = payload.collectionKeys self.valid = true return } } self.defaultBundle = KeyBundle.invalid self.valid = false } public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) { let f: (JSON) -> KeysPayload = { KeysPayload($0) } let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f)) self.init(payload: keysRecord?.payload) } public class func random() -> Keys { return Keys(defaultBundle: KeyBundle.random()) } public func forCollection(collection: String) -> KeyBundle { if let bundle = collectionKeys[collection] { return bundle } return defaultBundle } public func encrypter<T: CleartextPayloadJSON>(collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> { return RecordEncrypter(bundle: forCollection(collection), encoder: encoder) } public func asPayload() -> KeysPayload { let json: JSON = JSON([ "id": "keys", "collection": "crypto", "default": self.defaultBundle.asPair(), "collections": mapValues(self.collectionKeys, f: { $0.asPair() }) ]) return KeysPayload(json) } } /** * Yup, these are basically typed tuples. */ public struct RecordEncoder<T: CleartextPayloadJSON> { let decode: JSON -> T let encode: T -> JSON } public struct RecordEncrypter<T: CleartextPayloadJSON> { let serializer: Record<T> -> JSON? let factory: String -> T? init(bundle: KeyBundle, encoder: RecordEncoder<T>) { self.serializer = bundle.serializer(encoder.encode) self.factory = bundle.factory(encoder.decode) } init(serializer: Record<T> -> JSON?, factory: String -> T?) { self.serializer = serializer self.factory = factory } } public func ==(lhs: Keys, rhs: Keys) -> Bool { return lhs.valid == rhs.valid && lhs.defaultBundle == rhs.defaultBundle && lhs.collectionKeys == rhs.collectionKeys }
mpl-2.0
f546a603f302c15d0ba790b305d2ea4f
34.372483
145
0.600607
4.686972
false
false
false
false
DanijelHuis/HDAugmentedReality
HDAugmentedReality/Classes/Radar/RadarMapView.swift
1
20075
// // RadarMapView.swift // HDAugmentedRealityDemo // // Created by Danijel Huis on 15/07/2019. // Copyright © 2019 Danijel Huis. All rights reserved. // import UIKit import MapKit import SceneKit /** RadarMapView consists of: - MKMapView showing annotations - ring around map that shows out of bounds annotations (indicators) - zoom in/out and shrink/expand buttons RadarMapView gets annotations and all other data via ARAccessory delegate. Intended to be used with ARViewController. Usage: - RadarMapView must have height constraint in order to resize/shrink properly (. - use startMode and trackingMode properties to adjust how map zoom/tracking behaves on start and later on. - use configuration property to customize. Internal note: Problems with MKMapView: - setting anything on MKMapCamera will cancel current map annimation, e.g. setting heading will cause map to jump to location instead of smoothly animate. - setting heading everytime it changes will disable user interaction with map and cancel all animations. */ open class RadarMapView: UIView, ARAccessory, MKMapViewDelegate { public struct Configuration { /// Image for annotations that are shown on the map public var annotationImage = UIImage(named: "radarAnnotation", in: Bundle(for: RadarMapView.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) /// Image for user annotation that is shown on the map public var userAnnotationImage = UIImage(named: "radarUserAnnotation", in: Bundle(for: RadarMapView.self), compatibleWith: nil) /// Use it to set anchor point for your userAnnotationImage. This is where you center is on the image, in default image its on 201st pixel, image height is 240. public var userAnnotationAnchorPoint = CGPoint(x: 0.5, y: 201/240) /// Determines how much RadarMapView expands. public var radarSizeRatio: CGFloat = 1.75 /// If true, resize button will be placed in top right corner which resizes whole radar. public var isResizeEnabled = true /// If true, +/- buttons are placed in lower right cornert which control map zoom level. public var isZoomEnabled = true } //===== Public /// Defines map position and zoom at start. open var startMode: RadarStartMode = .centerUser(span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) /// Defines map position and zoom when user location changes. open var trackingMode: RadarTrackingMode = .centerUserWhenNearBorder(span: nil) /// Use it to configure and customize your radar. Must be done before RadarMapView is added to superview. open var configuration: Configuration = Configuration() /// If set it will show only annotations that are closer than given value (in meters). open var maxDistance: Double? /// Read MKAnnotationView.canShowCallout. open var annotationsCanShowCallout = false /// Radar ring type. open var indicatorRingType: IndicatorRingType = .none { didSet { self.updateIndicatorRingType() } } //===== IB @IBOutlet weak private(set) public var mapViewContainer: UIView! @IBOutlet weak private(set) public var mapView: MKMapView! @IBOutlet weak private(set) public var indicatorContainerView: UIView! @IBOutlet weak private(set) public var resizeButton: UIButton! @IBOutlet weak private(set) public var zoomInButton: UIButton! @IBOutlet weak private(set) public var zoomOutButton: UIButton! //===== Private private var isFirstZoom = true private var isReadyToReload = false private var radarAnnotations: [ARAnnotation] = [] private var userRadarAnnotation: ARAnnotation? private weak var userRadarAnnotationView: RadarAnnotationView? override open var bounds: CGRect { didSet { self.layoutUi() } } private var allRadarAnnotationsCount: Int = 0 //========================================================================================================================================================== // MARK: Init //========================================================================================================================================================== override init(frame: CGRect) { super.init(frame: frame) self.addSubviewFromNib() self.loadUi() self.bindUi() self.styleUi() self.layoutUi() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addSubviewFromNib() } override open func awakeFromNib() { super.awakeFromNib() self.loadUi() self.bindUi() self.styleUi() self.layoutUi() } //========================================================================================================================================================== // MARK: UI //========================================================================================================================================================== func loadUi() { self.isReadyToReload = true } func bindUi() { self.bindResizeButton() } func styleUi() { self.backgroundColor = .clear } func layoutUi() { self.mapView.setNeedsLayout() self.mapView.layoutIfNeeded() self.mapView.layer.cornerRadius = self.mapView.bounds.size.width / 2.0 self.indicatorContainerView.setNeedsLayout() self.indicatorContainerView.layoutIfNeeded() self.indicatorContainerView.layer.cornerRadius = self.indicatorContainerView.bounds.size.width / 2.0 self.resizeButton.isHidden = !self.configuration.isResizeEnabled self.zoomInButton.isHidden = !self.configuration.isZoomEnabled self.zoomOutButton.isHidden = !self.configuration.isZoomEnabled } override open func didMoveToSuperview() { super.didMoveToSuperview() if self.superview != nil { self.layoutUi() } } /// Can be called to reload some configuration properties. open func reload() { self.layoutUi() } //========================================================================================================================================================== // MARK: Reload //========================================================================================================================================================== /// This is called from ARPresenter open func reload(reloadType: ARViewController.ReloadType, status: ARStatus, presenter: ARPresenter) { guard self.isReadyToReload, let location = status.userLocation else { return } var didChangeAnnotations = false //===== Add/remove radar annotations if annotations changed if reloadType == .annotationsChanged || self.allRadarAnnotationsCount != presenter.annotations.count || (reloadType == .reloadLocationChanged && self.maxDistance != nil) { self.allRadarAnnotationsCount = presenter.annotations.count if let maxDistance = self.maxDistance { self.radarAnnotations = presenter.annotations.filter { $0.distanceFromUser <= maxDistance } } else { self.radarAnnotations = presenter.annotations } // Remove everything except the user annotation self.mapView.removeAnnotations(self.mapView.annotations.filter { $0 !== self.userRadarAnnotation }) self.mapView.addAnnotations(self.radarAnnotations) didChangeAnnotations = true } //===== Add/remove user map annotation when user location changes if [.reloadLocationChanged, .userLocationChanged].contains(reloadType) || self.userRadarAnnotation == nil { // It doesn't work if we just update annotation's coordinate, we have to remove it and add again. if let userRadarAnnotation = self.userRadarAnnotation { self.mapView.removeAnnotation(userRadarAnnotation) self.userRadarAnnotation = nil } if let newUserRadarAnnotation = ARAnnotation(identifier: "userRadarAnnotation", title: nil, location: location) { self.mapView.addAnnotation(newUserRadarAnnotation) self.userRadarAnnotation = newUserRadarAnnotation } didChangeAnnotations = true } //===== Track user (map position and zoom) if self.isFirstZoom || [.reloadLocationChanged, .userLocationChanged].contains(reloadType) { let isFirstZoom = self.isFirstZoom self.isFirstZoom = false if isFirstZoom { if case .centerUser(let span) = self.startMode { let region = MKCoordinateRegion(center: location.coordinate, span: span) self.mapView.setRegion(self.mapView.regionThatFits(region), animated: false) } else if case .fitAnnotations = self.startMode { self.setRegionToAnntations(animated: false) } } else { if case .centerUserAlways(let trackingModeSpan) = self.trackingMode { let span = trackingModeSpan ?? self.mapView.region.span let region = MKCoordinateRegion(center: location.coordinate, span: span) self.mapView.setRegion(self.mapView.regionThatFits(region), animated: true) } else if case .centerUserWhenNearBorder(let trackingModeSpan) = self.trackingMode { if self.isUserRadarAnnotationNearOrOverBorder { let span = trackingModeSpan ?? self.mapView.region.span let region = MKCoordinateRegion(center: location.coordinate, span: span) self.mapView.setRegion(self.mapView.regionThatFits(region), animated: true) } } } } //===== Heading self.userRadarAnnotationView?.heading = status.heading //===== Indicators if didChangeAnnotations { self.updateIndicators() } } //========================================================================================================================================================== // MARK: MKMapViewDelegate //========================================================================================================================================================== public func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // User annotation if annotation === self.userRadarAnnotation { let reuseIdentifier = "userRadarAnnotation" let view = (mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as! RadarAnnotationView?) ?? RadarAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier) view.annotation = annotation if #available(iOS 11.0, *) { view.displayPriority = .required } view.canShowCallout = false view.isSelected = true // Keeps it above other annotations (hopefully) view.imageView?.image = self.configuration.userAnnotationImage view.imageView?.layer.anchorPoint = self.configuration.userAnnotationAnchorPoint view.frame.size = self.configuration.userAnnotationImage?.size ?? CGSize(width: 100, height: 100) self.userRadarAnnotationView = view return view } // Other annotations else { let reuseIdentifier = "radarAnnotation" let view = (mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as! RadarAnnotationView?) ?? RadarAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier) view.annotation = annotation if #available(iOS 11.0, *) { view.displayPriority = .required } view.canShowCallout = self.annotationsCanShowCallout let radarAnnotation = annotation as? RadarAnnotation view.imageView?.image = radarAnnotation?.radarAnnotationImage ?? self.configuration.annotationImage view.imageView?.tintColor = radarAnnotation?.radarAnnotationTintColor ?? nil view.frame.size = CGSize(width: 9, height: 9) return view } } public func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) { self.updateIndicators() } //========================================================================================================================================================== // MARK: Indicators //========================================================================================================================================================== private var lastTimeInterval: TimeInterval = Date().timeIntervalSince1970 private var indicatorsRefreshInterval: Double = 1/25 private(set) open var indicatorRing: IndicatorRingProtocol? private func updateIndicatorRingType() { self.indicatorRing?.removeFromSuperview() self.indicatorRing = nil var indicatorRing: IndicatorRingProtocol? switch self.indicatorRingType { case .none: break case .segmented(let segmentColor, let userSegmentColor): let segmentedIndicatorRing = SegmentedIndicatorRing(frame: .zero) if let segmentColor = segmentColor { segmentedIndicatorRing.segmentColor = segmentColor.cgColor } if let userSegmentColor = userSegmentColor { segmentedIndicatorRing.userSegmentColor = userSegmentColor.cgColor } indicatorRing = segmentedIndicatorRing case .precise(let indicatorColor, let userIndicatorColor): let preciseIndicatorRing = PreciseIndicatorRing(frame: .zero) if let userIndicatorColor = userIndicatorColor { preciseIndicatorRing.userIndicatorColor = userIndicatorColor } if let indicatorColor = indicatorColor { preciseIndicatorRing.indicatorColor = indicatorColor } indicatorRing = preciseIndicatorRing break case .custom(let customIndicatorRing): indicatorRing = customIndicatorRing } if let indicatorRing = indicatorRing { indicatorRing.translatesAutoresizingMaskIntoConstraints = false self.indicatorContainerView.addSubview(indicatorRing) indicatorRing.pinToSuperview(leading: 0, trailing: 0, top: 0, bottom: 0, width: nil, height: nil) self.indicatorRing = indicatorRing } } /** Updates indicators position. */ private func updateIndicators() { let currentTimeInterval = Date().timeIntervalSince1970 if abs(self.lastTimeInterval - currentTimeInterval) < self.indicatorsRefreshInterval { return; } self.indicatorRing?.update(mapView: self.mapView, userAnnotation: self.userRadarAnnotation) } /** Returns true if user annotation is near or over border of the map. */ private var isUserRadarAnnotationNearOrOverBorder: Bool { let mapRadius = Double(self.mapView.frame.size.width) / 2 guard let annotation = self.userRadarAnnotation, mapRadius > 30 else { return false } let threshold = mapRadius * 0.4 let mapCenter = simd_double2(x: mapRadius, y: mapRadius) let annotationCenterCGPoint = self.mapView.convert(annotation.coordinate, toPointTo: self.mapView) let annotationCenter = simd_double2(x: Double(annotationCenterCGPoint.x) , y: Double(annotationCenterCGPoint.y)) let centerToAnnotationVector = annotationCenter - mapCenter return simd_length(centerToAnnotationVector) > (mapRadius - threshold) } //========================================================================================================================================================== // MARK: Utility //========================================================================================================================================================== /** Zooms map by given factor. */ open func zoomMap(by factor: Double, animated: Bool) { var region: MKCoordinateRegion = self.mapView.region var span: MKCoordinateSpan = self.mapView.region.span span.latitudeDelta *= factor span.longitudeDelta *= factor region.span = span self.mapView.setRegion(region, animated: animated) } /** Zooms map to fit all annotations (considering rounded map). */ open func setRegionToAnntations(animated: Bool) { var zoomRect = MKMapRect.null let edgePadding = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) // Maybe make ratio of map size? for annotation in self.mapView.annotations { let annotationPoint = MKMapPoint(annotation.coordinate) let annotationRect = MKMapRect(x: annotationPoint.x, y: annotationPoint.y, width: 0.1, height: 0.1) zoomRect = zoomRect.union(annotationRect) } if zoomRect.width > 0 || zoomRect.height > 0 { self.mapView.setVisibleMapRect(zoomRect, edgePadding: edgePadding, animated: animated) } } private var isResized: Bool = false private var heightBeforeResizing: CGFloat? private func resizeRadar() { if self.heightBeforeResizing == nil { self.heightBeforeResizing = self.frame.size.height } guard let heightConstraint = self.findConstraint(attribute: .height), let heightBeforeResizing = self.heightBeforeResizing else { print("Cannot resize, RadarMapView must have height constraint.") return } self.isResized = !self.isResized heightConstraint.constant = self.isResized ? heightBeforeResizing * self.configuration.radarSizeRatio : heightBeforeResizing UIView.animate(withDuration: 1/3, animations: { self.superview?.layoutIfNeeded() self.bindResizeButton() self.updateIndicators() }) { (finished) in self.mapView.setNeedsLayout() // Needed because of legal label. } } private func bindResizeButton() { self.resizeButton.isSelected = self.isResized } //========================================================================================================================================================== // MARK: User interaction //========================================================================================================================================================== @IBAction func sizeButtonTapped(_ sender: Any) { self.resizeRadar() } @IBAction func zoomInButtonTapped(_ sender: Any) { self.zoomMap(by: 75/100, animated: false) } @IBAction func zoomOutButtonTapped(_ sender: Any) { self.zoomMap(by: 100/75, animated: false) } }
mit
a4f80e19dbe0c91dd0f6237ba383a742
44.211712
201
0.563415
5.793362
false
false
false
false
tensorflow/swift-models
SwiftModelsBenchmarksCore/Models/WordSeg.swift
1
4909
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Benchmark import Datasets import ModelSupport import TensorFlow import TextModels #if os(Windows) #if canImport(CRT) import CRT #else import MSVCRT #endif #endif let WordSegScore = wordSegSuite( name: "WordSegScore", operation: score) let WordSegScoreAndGradient = wordSegSuite( name: "WordSegScoreAndGradient", operation: scoreAndGradient) let WordSegViterbi = wordSegSuite( name: "WordSegViterbi", operation: viterbi) let maximumSequenceLength = 18 func wordSegSuite(name: String, operation: @escaping (SNLM, CharacterSequence, Device) -> Void) -> BenchmarkSuite { let function = wordSegBenchmark(operation) let columns = Columns([ "name", "wall_time", "startup_time", "iterations", "time_median", "time_min", "time_max", ]) return BenchmarkSuite(name: name, settings: WarmupIterations(10), columns) { suite in suite.benchmark( "sentence_4", settings: Length(4), Backend(.eager), function: function) suite.benchmark( "sentence_4_x10", settings: Length(4), Backend(.x10), function: function) suite.benchmark( "sentence_8", settings: Length(8), Backend(.eager), function: function) suite.benchmark( "sentence_8_x10", settings: Length(8), Backend(.x10), function: function) suite.benchmark( "sentence_14", settings: Length(14), Backend(.eager), function: function) suite.benchmark( "sentence_14_x10", settings: Length(14), Backend(.x10), function: function) } } func wordSegBenchmark(_ operation: @escaping (SNLM, CharacterSequence, Device) -> Void) -> ( (inout BenchmarkState) throws -> Void ) { return { state in let settings = state.settings let device = settings.device let length = settings.length! state.start() let dataset: WordSegDataset if let trainingFilePath = settings.datasetFilePath { dataset = try WordSegDataset(training: trainingFilePath) } else { dataset = try WordSegDataset() } let sentence = try testSentence( length: length, alphabet: dataset.alphabet) // Model settings are drawn from known benchmarks. let lexicon = Lexicon( from: [sentence], alphabet: dataset.alphabet, maxLength: maximumSequenceLength, minFrequency: 10 ) let modelParameters = SNLM.Parameters( hiddenSize: 512, dropoutProbability: 0.5, alphabet: dataset.alphabet, lexicon: lexicon, order: 5 ) var model = SNLM(parameters: modelParameters) model.move(to: device) while true { operation(model, sentence, device) LazyTensorBarrier() do { try state.end() } catch { if settings.backend == .x10 { // A synchronous barrier is needed for X10 to ensure all execution completes // before tearing down the model. LazyTensorBarrier(wait: true) } throw error } state.start() } } } func testSentence(length: Int, alphabet: Alphabet) throws -> CharacterSequence { let sourceSentence = [ "you", "like", "daddy's", "whiskers", "just", "gonna", "eat", "the", "comb", "and", "that's", "all", ] let truncatedSentence = sourceSentence.prefix(length).reduce("", +) // + ["</s"] return try CharacterSequence(alphabet: alphabet, appendingEoSTo: truncatedSentence) } func score(model: SNLM, sentence: CharacterSequence, device: Device) { let lattice = model.buildLattice(sentence, maxLen: maximumSequenceLength, device: device) let score = lattice[sentence.count].semiringScore let _ = score.logr + score.logp } func scoreAndGradient(model: SNLM, sentence: CharacterSequence, device: Device) { let lambd: Float = 0.00075 let _ = valueWithGradient(at: model) { model -> Tensor<Float> in let lattice = model.buildLattice(sentence, maxLen: maximumSequenceLength, device: device) let score = lattice[sentence.count].semiringScore let expectedLength = exp(score.logr - score.logp) let loss = -1 * score.logp + lambd * expectedLength return Tensor(loss, on: device) } } func viterbi(model: SNLM, sentence: CharacterSequence, device: Device) { var lattice = model.buildLattice(sentence, maxLen: maximumSequenceLength, device: device) let _ = lattice.viterbi(sentence: sentence) }
apache-2.0
91fbc812810fa7dd5978bfca48763f70
29.302469
95
0.689142
3.817263
false
false
false
false
DannyKG/BoLianEducation
BoLianEducation/Task/ViewController/TaskSearchController.swift
1
12182
// // TaskSearchController.swift // BoLianEducation // // Created by BoLian on 2017/6/13. // Copyright © 2017年 BoLian. All rights reserved. // import UIKit class TaskSearchController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { var dataSource = Array<Array<Any>>() var boolArray = Array<Array<Bool>>() var currentIndexPath: IndexPath? var taskType: String! var topHiden = true lazy var searchCollectionView: UICollectionView = { let barHeight = 100 * ApplicationStyle.proportion_weight() let flowLayout = LeftAlignedLayoutSwift.init() flowLayout.minimumLineSpacing = 15 flowLayout.minimumInteritemSpacing = 15 flowLayout.scrollDirection = UICollectionViewScrollDirection.vertical let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: barHeight, width: KUIScreenWidth, height: KUIScreenHeight - kNavigationBarHeight - barHeight - 88 * ApplicationStyle.proportion_weight()), collectionViewLayout: flowLayout) collectionView.backgroundColor = MainRGBColor collectionView.delegate = self collectionView.dataSource = self collectionView.showsVerticalScrollIndicator = false return collectionView }() lazy var searchBar: RCDSearchBar = { let barHeight = 60 * ApplicationStyle.proportion_weight() let totalHeight = 100 * ApplicationStyle.proportion_weight() let bar = RCDSearchBar.init(frame: CGRect.init(x: 0, y: (totalHeight - barHeight)/2.0, width: KUIScreenWidth, height: barHeight)) bar.delegate = (self as UISearchBarDelegate) return bar }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. addSubViews() getAllLabes() } //MARK:网络请求 func getAllLabes() { let model = TaskReleaseModel() model.resultBlock = { [weak self] (response: Any) in self?.analysisData(data: response) } model.errorBlock = { (error: Any) in let errorObject = error as AnyObject if errorObject.isKind!(of: NSString.self) { MBProgressHUD.showError(errorObject as! String) } } if let account = AccountTool.shared().account { model.getTaskLabels(taskType, number: 20, ownId: account.userId) } } func analysisData(data: Any) { let result = data as! Array<Any> if result.count == 2 { let subArray = result[0] as! Array<Array<Any>> dataSource = subArray boolArray = result[1] as! Array<Array<Bool>> if topHiden { dataSource.insert([], at: 0) boolArray.insert([], at: 0) } searchCollectionView.reloadData() } } func addSubViews() { view.backgroundColor = UIColor.white title = "查找任务" let topView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: KUIScreenWidth, height: 100 * ApplicationStyle.proportion_weight())) topView.backgroundColor = UIColor.white topView.addSubview(searchBar) view.addSubview(topView) view.addSubview(searchCollectionView) registerCollectionViewCell() bottomButton() } func bottomButton() { let buttonHeight = 88 * ApplicationStyle.proportion_weight() let originY = KUIScreenHeight - kNavigationBarHeight - buttonHeight let button = UIButton.init(type: UIButtonType.custom) button.frame = CGRect.init(x: 0, y: originY, width: KUIScreenWidth, height: buttonHeight) button.backgroundColor = UIColor.white button.setTitle("查找", for: UIControlState.normal) button.titleLabel?.font = ApplicationStyle.textBigFont() button.setTitleColor(UIColor.white, for: UIControlState.normal) button.backgroundColor = MainBlueColor button.adjustsImageWhenHighlighted = false button.addTarget(self, action: #selector(buttonAction(sender:)), for: UIControlEvents.touchUpInside) view.addSubview(button) } func registerCollectionViewCell() { searchCollectionView.register(UINib.init(nibName: "TaskSearchCollectionCell", bundle: Bundle.main), forCellWithReuseIdentifier: NSStringFromClass(TaskSearchCollectionCell.self)) searchCollectionView.register(UINib.init(nibName: "LabelHeaaderReusableView", bundle: Bundle.main),forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: NSStringFromClass(LabelHeaaderReusableView.self)) searchCollectionView.register(SearchHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: NSStringFromClass(SearchHeaderView.self)) } func buttonAction(sender: UIButton) { let resultVC = SearchResultController() if let indexPath = currentIndexPath { if topHiden { if let headerView = searchCollectionView.viewWithTag(440) as? SearchHeaderView { resultVC.boolArray = headerView.boolArray! } } else { let boolArray = [false, true, false] resultVC.boolArray = boolArray } let subArray = dataSource[indexPath.section][indexPath.row] as! Array<Any> let title = subArray[0] as! String resultVC.searchLabel = title resultVC.taskType = taskType self.navigationController?.pushViewController(resultVC, animated: true) } else { MBProgressHUD.showText("请选择标签") } } //MARK -- dataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if topHiden { if section == 0 { return 0 } } return dataSource[section].count } func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if topHiden { if indexPath.section == 0 { return CGSize.zero } } let subArray = dataSource[indexPath.section][indexPath.row] as! Array<Any> let title = subArray[0] as! String var sizeWidth:CGFloat = 30 let size = ApplicationStyle.textSize(title, font: ApplicationStyle.textSmallFont(), size: 78) sizeWidth += size.width return CGSize.init(width: sizeWidth, height: 88 * ApplicationStyle.proportion_weight()) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { var bottom = 15 if topHiden { if 0 == section { bottom = 0 } } return UIEdgeInsetsMake(CGFloat(bottom), 15, 15, 15) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { if topHiden { if section == 0 { return CGSize.init(width: KUIScreenWidth, height: 5 + 3 * 88 * ApplicationStyle.proportion_weight()) } } return CGSize.init(width: KUIScreenWidth, height: 24 + ApplicationStyle.textMediumFont().lineHeight) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { if topHiden { if indexPath.section == 0 { let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: NSStringFromClass(SearchHeaderView.self), for: indexPath) as! SearchHeaderView reusableView.tag = 440 return reusableView } } let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: NSStringFromClass(LabelHeaaderReusableView.self), for: indexPath) as! LabelHeaaderReusableView reusableView.backgroundColor = UIColor.white var section = 0 if topHiden { section = 1 } if indexPath.section == section { reusableView.textTitle = "推荐标签" } else { reusableView.textTitle = "自定义标签" } return reusableView } else { return UICollectionReusableView.init() } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(TaskSearchCollectionCell.self), for: indexPath) as! TaskSearchCollectionCell let subArray = dataSource[indexPath.section][indexPath.row] as! Array<Any> let title = subArray[0] as! String cell.taskTitle = title cell.isImageSelected = boolArray[indexPath.section][indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { view.endEditing(true) let cell = collectionView.cellForItem(at: indexPath) as! TaskSearchCollectionCell //var isTrue: Bool = false if let path = currentIndexPath { if path != indexPath { let currentCell = collectionView.cellForItem(at: path) as! TaskSearchCollectionCell currentCell.isImageSelected = false cell.isImageSelected = true boolArray[path.section][path.row] = false boolArray[indexPath.section][indexPath.row] = true } } else { cell.isImageSelected = true boolArray[indexPath.section][indexPath.row] = true } currentIndexPath = indexPath /* for item in 0..<boolArray.count { if isTrue { break } for index in 0..<boolArray[item].count { isTrue = boolArray[item][index] if isTrue { boolArray[item][index] = false let selectedIndexPath = NSIndexPath.init(item: index, section: item + 1) let selectedCell = collectionView.cellForItem(at: selectedIndexPath as IndexPath) as! TaskSearchCollectionCell selectedCell.isImageSelected = false break } } } cell.isImageSelected = true boolArray[indexPath.section - 1][indexPath.row] = true */ } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { view.endEditing(true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if searchBar.isFirstResponder { searchBar.resignFirstResponder() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension TaskSearchController: TaskSearchReusableViewDelegate, UISearchBarDelegate { func buttonChanged(tag: Int) { } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { let resultVC = SearchResultController() if !topHiden { let boolArray = [false, true, false] resultVC.boolArray = boolArray } resultVC.taskType = taskType self.navigationController?.pushViewController(resultVC, animated: true) } }
apache-2.0
ba93648084aafadbe0a38e9ab82b9b86
40.544521
251
0.637623
5.408382
false
false
false
false
mikaoj/BSImagePicker
Sources/Scene/Albums/AlbumsTableViewDataSource.swift
1
3424
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 Photos /** Implements the UITableViewDataSource protocol with a data source and cell factory */ final class AlbumsTableViewDataSource : NSObject, UITableViewDataSource { var settings: Settings! private let albums: [PHAssetCollection] private let scale: CGFloat private let imageManager = PHCachingImageManager.default() init(albums: [PHAssetCollection], scale: CGFloat = UIScreen.main.scale) { self.albums = albums self.scale = scale super.init() } func numberOfSections(in tableView: UITableView) -> Int { return albums.count > 0 ? 1 : 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return albums.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: AlbumCell.identifier, for: indexPath) as! AlbumCell // Fetch album let album = albums[indexPath.row] // Title cell.albumTitleLabel.attributedText = titleForAlbum(album) let fetchOptions = settings.fetch.assets.options.copy() as! PHFetchOptions fetchOptions.fetchLimit = 1 let imageSize = CGSize(width: 84, height: 84).resize(by: scale) let imageContentMode: PHImageContentMode = .aspectFill if let asset = PHAsset.fetchAssets(in: album, options: fetchOptions).firstObject { imageManager.requestImage(for: asset, targetSize: imageSize, contentMode: imageContentMode, options: settings.fetch.preview.photoOptions) { (image, _) in guard let image = image else { return } cell.albumImageView.image = image } } return cell } func registerCells(in tableView: UITableView) { tableView.register(AlbumCell.self, forCellReuseIdentifier: AlbumCell.identifier) } private func titleForAlbum(_ album: PHAssetCollection) -> NSAttributedString { let text = NSMutableAttributedString() text.append(NSAttributedString(string: album.localizedTitle ?? "", attributes: settings.theme.albumTitleAttributes)) return text } }
mit
ce2f079c84a66086abfa2f34433ca064
39.270588
165
0.701724
5.041237
false
false
false
false
xin-wo/kankan
kankan/Pods/Kingfisher/Sources/ImageDownloader.swift
5
22569
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2016 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(OSX) import AppKit #else import UIKit #endif /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((image: Image?, error: NSError?, imageURL: NSURL?, originalData: NSData?) -> ()) /// Download task. public struct RetrieveImageDownloadTask { let internalTask: NSURLSessionDataTask /// Downloader by which this task is intialized. public private(set) weak var ownerDownloader: ImageDownloader? /** Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. */ public func cancel() { ownerDownloader?.cancelDownloadingTask(self) } /// The original request URL of this download task. public var URL: NSURL? { return internalTask.originalRequest?.URL } /// The relative priority of this download task. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. /// The value for it is between 0.0~1.0. Default priority is value of 0.5. /// See documentation on `priority` of `NSURLSessionTask` for more about it. public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } } } private let defaultDownloaderName = "default" private let downloaderBarrierName = "com.onevcat.Kingfisher.ImageDownloader.Barrier." private let imageProcessQueueName = "com.onevcat.Kingfisher.ImageDownloader.Process." private let instance = ImageDownloader(name: defaultDownloaderName) /** The error code. - BadData: The downloaded data is not an image or the data is corrupted. - NotModified: The remote server responsed a 304 code. No image data downloaded. - NotCached: The image rquested is not in cache but OnlyFromCache is activated. - InvalidURL: The URL is invalid. */ public enum KingfisherError: Int { case BadData = 10000 case NotModified = 10001 case InvalidStatusCode = 10002 case NotCached = 10003 case InvalidURL = 20000 } /// Protocol of `ImageDownloader`. @objc public protocol ImageDownloaderDelegate { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. - parameter downloader: The `ImageDownloader` object finishes the downloading. - parameter image: Downloaded image. - parameter URL: URL of the original request URL. - parameter response: The response object of the downloading process. */ optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: Image, forURL URL: NSURL, withResponse response: NSURLResponse) } /// Protocol indicates that an authentication challenge could be handled. public protocol AuthenticationChallengeResponable: class { /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`. */ func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) } extension AuthenticationChallengeResponable { func downloader(downloader: ImageDownloader, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) { let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!) completionHandler(.UseCredential, credential) return } } completionHandler(.PerformDefaultHandling, nil) } } /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. public class ImageDownloader: NSObject { class ImageFetchLoad { var callbacks = [CallbackPair]() var responseData = NSMutableData() var options: KingfisherOptionsInfo? var downloadTaskCount = 0 var downloadTask: RetrieveImageDownloadTask? } // MARK: - Public property /// This closure will be applied to the image download request before it being sent. You can modify the request for some customizing purpose, like adding auth token to the header or do a url mapping. public var requestModifier: (NSMutableURLRequest -> Void)? /// The duration before the download is timeout. Default is 15 seconds. public var downloadTimeout: NSTimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. public var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. public var sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() { didSet { session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue()) } } /// Whether the download requests should use pipeling or not. Default is false. public var requestsUsePipeling = false private let sessionHandler: ImageDownloaderSessionHandler private var session: NSURLSession? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. public weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. public weak var authenticationChallengeResponder: AuthenticationChallengeResponable? // MARK: - Internal property let barrierQueue: dispatch_queue_t let processQueue: dispatch_queue_t typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHander: ImageDownloaderCompletionHandler?) var fetchLoads = [NSURL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public class var defaultDownloader: ImageDownloader { return instance } /** Init a downloader with name. - parameter name: The name for the downloader. It should not be empty. - returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT) processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_CONCURRENT) sessionHandler = ImageDownloaderSessionHandler() super.init() // Provide a default implement for challenge responder. authenticationChallengeResponder = sessionHandler session = NSURLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: NSOperationQueue.mainQueue()) } func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? dispatch_sync(barrierQueue, { () -> Void in fetchLoad = self.fetchLoads[key] }) return fetchLoad } } // MARK: - Download method extension ImageDownloader { /** Download an image with a URL. - parameter URL: Target URL. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ public func downloadImageWithURL(URL: NSURL, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { return downloadImageWithURL(URL, options: nil, progressBlock: progressBlock, completionHandler: completionHandler) } /** Download an image with a URL and option. - parameter URL: Target URL. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ public func downloadImageWithURL(URL: NSURL, options: KingfisherOptionsInfo?, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { return downloadImageWithURL(URL, retrieveImageTask: nil, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } internal func downloadImageWithURL(URL: NSURL, retrieveImageTask: RetrieveImageTask?, options: KingfisherOptionsInfo?, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { if let retrieveImageTask = retrieveImageTask where retrieveImageTask.cancelledBeforeDownloadStarting { return nil } let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout) request.HTTPShouldUsePipelining = requestsUsePipeling self.requestModifier?(request) // There is a possiblility that request modifier changed the url to `nil` or empty. #if swift(>=2.3) let isEmptyUrl = (request.URL == nil || request.URL!.absoluteString == nil || (request.URL!.absoluteString!.isEmpty)) #else let isEmptyUrl = (request.URL == nil || request.URL!.absoluteString.isEmpty) #endif if isEmptyUrl { completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidURL.rawValue, userInfo: nil), imageURL: nil, originalData: nil) return nil } var downloadTask: RetrieveImageDownloadTask? setupProgressBlock(progressBlock, completionHandler: completionHandler, forURL: request.URL!) {(session, fetchLoad) -> Void in if fetchLoad.downloadTask == nil { let dataTask = session.dataTaskWithRequest(request) fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) fetchLoad.options = options dataTask.priority = options?.downloadPriority ?? NSURLSessionTaskPriorityDefault dataTask.resume() // Hold self while the task is executing. self.sessionHandler.downloadHolder = self } fetchLoad.downloadTaskCount += 1 downloadTask = fetchLoad.downloadTask retrieveImageTask?.downloadTask = downloadTask } return downloadTask } // A single key may have multiple callbacks. Only download once. internal func setupProgressBlock(progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?, forURL URL: NSURL, started: ((NSURLSession, ImageFetchLoad) -> Void)) { dispatch_barrier_sync(barrierQueue, { () -> Void in let loadObjectForURL = self.fetchLoads[URL] ?? ImageFetchLoad() let callbackPair = (progressBlock: progressBlock, completionHander: completionHandler) loadObjectForURL.callbacks.append(callbackPair) self.fetchLoads[URL] = loadObjectForURL if let session = self.session { started(session, loadObjectForURL) } }) } func cancelDownloadingTask(task: RetrieveImageDownloadTask) { dispatch_barrier_sync(barrierQueue) { () -> Void in if let URL = task.internalTask.originalRequest?.URL, imageFetchLoad = self.fetchLoads[URL] { imageFetchLoad.downloadTaskCount -= 1 if imageFetchLoad.downloadTaskCount == 0 { task.internalTask.cancel() } } } } func cleanForURL(URL: NSURL) { dispatch_barrier_sync(barrierQueue, { () -> Void in self.fetchLoads.removeValueForKey(URL) return }) } } // MARK: - NSURLSessionDataDelegate // See https://github.com/onevcat/Kingfisher/issues/235 /// Delegate class for `NSURLSessionTaskDelegate`. /// The session object will hold its delegate until it gets invalidated. /// If we use `ImageDownloader` as the session delegate, it will not be released. /// So we need an additional handler to break the retain cycle. class ImageDownloaderSessionHandler: NSObject, NSURLSessionDataDelegate, AuthenticationChallengeResponable { // The holder will keep downloader not released while a data task is being executed. // It will be set when the task started, and reset when the task finished. var downloadHolder: ImageDownloader? /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { // If server response is not 200,201 or 304, inform the callback handler with InvalidStatusCode error. // InvalidStatusCode error has userInfo which include statusCode and localizedString. if let statusCode = (response as? NSHTTPURLResponse)?.statusCode, let URL = dataTask.originalRequest?.URL where statusCode != 200 && statusCode != 201 && statusCode != 304 { callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidStatusCode.rawValue, userInfo: ["statusCode": statusCode, "localizedStringForStatusCode": NSHTTPURLResponse.localizedStringForStatusCode(statusCode)]), imageURL: URL, originalData: nil) } completionHandler(NSURLSessionResponseDisposition.Allow) } /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { guard let downloader = downloadHolder else { return } if let URL = dataTask.originalRequest?.URL, fetchLoad = downloader.fetchLoadForKey(URL) { fetchLoad.responseData.appendData(data) for callbackPair in fetchLoad.callbacks { dispatch_async(dispatch_get_main_queue(), { () -> Void in callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength) }) } } } /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let URL = task.originalRequest?.URL { if let error = error { // Error happened callbackWithImage(nil, error: error, imageURL: URL, originalData: nil) } else { //Download finished without error processImageForTask(task, URL: URL) } } } /** This method is exposed since the compiler requests. Do not call it. */ internal func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloader(downloader, didReceiveChallenge: challenge, completionHandler: completionHandler) } private func callbackWithImage(image: Image?, error: NSError?, imageURL: NSURL, originalData: NSData?) { guard let downloader = downloadHolder else { return } if let callbackPairs = downloader.fetchLoadForKey(imageURL)?.callbacks { let options = downloader.fetchLoadForKey(imageURL)?.options ?? KingfisherEmptyOptionsInfo downloader.cleanForURL(imageURL) for callbackPair in callbackPairs { dispatch_async_safely_to_queue(options.callbackDispatchQueue, { () -> Void in callbackPair.completionHander?(image: image, error: error, imageURL: imageURL, originalData: originalData) }) } if downloader.fetchLoads.isEmpty { downloadHolder = nil } } } private func processImageForTask(task: NSURLSessionTask, URL: NSURL) { guard let downloader = downloadHolder else { return } // We are on main queue when receiving this. dispatch_async(downloader.processQueue, { () -> Void in if let fetchLoad = downloader.fetchLoadForKey(URL) { let options = fetchLoad.options ?? KingfisherEmptyOptionsInfo if let image = Image.kf_imageWithData(fetchLoad.responseData, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) { downloader.delegate?.imageDownloader?(downloader, didDownloadImage: image, forURL: URL, withResponse: task.response!) if options.backgroundDecode { self.callbackWithImage(image.kf_decodedImage(scale: options.scaleFactor), error: nil, imageURL: URL, originalData: fetchLoad.responseData) } else { self.callbackWithImage(image, error: nil, imageURL: URL, originalData: fetchLoad.responseData) } } else { // If server response is 304 (Not Modified), inform the callback handler with NotModified error. // It should be handled to get an image from cache, which is response of a manager object. if let res = task.response as? NSHTTPURLResponse where res.statusCode == 304 { self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotModified.rawValue, userInfo: nil), imageURL: URL, originalData: nil) return } self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil) } } else { self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL, originalData: nil) } }) } }
mit
ddf1f6cb3f2bde1298e98bba976acb21
44.965377
429
0.675794
5.689186
false
false
false
false
neotron/SwiftBot-Discord
Science Stuff.playground/Contents.swift
1
1469
//: Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" extension Double{ var toRadians: Double { return self * M_PI / 180.0 } var toDegrees: Double { return self * 180.0 / M_PI } } typealias LatLong = (lat: Double, lon: Double) private func calculateBearing(start: LatLong, end: LatLong, radius: Double?) -> (bearing: Double, distance: Double) { let λ1 = start.lat.toRadians let λ2 = end.lat.toRadians let φ1 = start.lon.toRadians let φ2 = end.lon.toRadians let y = sin(λ2-λ1) * cos(φ2) let x = cos(φ1)*sin(φ2) - sin(φ1)*cos(φ2)*cos(λ2-λ1) let bearing = (atan2(y, x).toDegrees + 450)%360 var distance = 0.0 if let R = radius { let Δφ = (end.lat-start.lat).toRadians let Δλ = (end.lon-start.lon).toRadians let a = sin(Δφ/2) * sin(Δφ/2) + cos(φ1) * cos(φ2) * sin(Δλ/2) * sin(Δλ/2); let c = 2 * atan2(sqrt(a), sqrt(1-a)); distance = R * c } return (bearing, distance) } let result = calculateBearing((-67.5169, -96.0039), end: (-66.88, -96.0), radius: 507.0) print("Bearing = \(result.bearing), distance: \(result.distance*1000) m") calculateBearing((10,10), end: (11,10), radius: 6500.0) calculateBearing((10,10), end: (10,11), radius: 6500.0) calculateBearing((10,10), end: (10,9), radius: 6500.0) calculateBearing((10,10), end: (9,10), radius: 6500.0)
gpl-3.0
88edd317f20f6cf1a2ec9ad78b22197b
28.428571
117
0.603329
2.8
false
false
false
false
iOSDevLog/InkChat
InkChat/Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallZigZag.swift
1
2579
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallZigZag: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 0.7 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize: CGFloat = size.width / 5 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) // Circle 1 animation let animation = CAKeyframeAnimation(keyPath:"transform") animation.keyTimes = [0.0, 0.33, 0.66, 1.0] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false let circle1 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) layer.addSublayer(circle1) // Circle 2 animation animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] let circle2 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) layer.addSublayer(circle2) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallZigZag { func makeCircleLayer(frame: CGRect, size: CGSize, color: UIColor, animation: CAAnimation) -> CALayer { let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color) circle.frame = frame circle.add(animation, forKey: "animation") return circle } }
apache-2.0
62f336820d940c9e35e1602efee0bf6d
41.278689
136
0.685537
4.630162
false
false
false
false
time-fighters/patachu
Time Fighter/BackgroundParallax.swift
1
3071
// // BackgroundParallax.swift // Time Fighter // // Created by Paulo Henrique Favero Pereira on 7/1/17. // Copyright © 2017 Fera. All rights reserved. // import UIKit import SpriteKit public class BackgroundParallax: SKNode { var currentSprite: SKSpriteNode var nextSprite: SKSpriteNode public init(spriteName: String) { self.currentSprite = SKSpriteNode(imageNamed: spriteName) self.nextSprite = self.currentSprite.copy() as! SKSpriteNode super.init() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// - speed: Speed of left moviment public func moveSprite(withSpeed speed: Float, deltaTime: TimeInterval, scene: SKScene) -> Void { var newPosition = CGPoint.zero //FIX ME: Passar a camera como parametro let camera = scene.childNode(withName: "mainCamera") // For both the sprite and its duplicate: for spriteToMove in [currentSprite, nextSprite] { // Shift the sprite leftward based on the speed newPosition = spriteToMove.position newPosition.x -= CGFloat(speed * Float(deltaTime)) spriteToMove.position = newPosition // If this sprite is now offscreen (i.e., its rightmost edge is // farther left than the scene's leftmost edge): if spriteToMove.frame.maxX < camera!.frame.minX + scene.frame.minX { // Shift it over so that it's now to the immediate right // of the other sprite. // This means that the two sprites are effectively // leap-frogging each other as they both move. spriteToMove.position = CGPoint(x: spriteToMove.position.x + spriteToMove.size.width * 2, y: spriteToMove.position.y) } } } /// Set the configuration for spriteNode and add it on Scene Background /// /// - Parameters: /// - sprite: Sprite to configurate /// - zpostion: Position on z axes on the scene /// - anchorPoint: anchor point of sprite /// - screenPosition: Desired postion to set on screen /// - spriteSize: Sprite size value public func createBackgroundNode(zpostion: CGFloat, anchorPoint: CGPoint, screenPosition:CGPoint, spriteSize: CGSize, scene:SKScene) { //set z position of sprite currentSprite.zPosition = zpostion //Set the anchor point currentSprite.anchorPoint = anchorPoint //Set the sprite position currentSprite.position = screenPosition currentSprite.size = spriteSize scene.addChild(currentSprite) nextSprite = (currentSprite.copy() as? SKSpriteNode)! nextSprite.position = CGPoint(x: screenPosition.x + (currentSprite.size.width), y: screenPosition.y) scene.addChild(nextSprite) } }
mit
82b0a3d7fb21fd7478fea52a7fd2e8f0
33.111111
139
0.614007
4.796875
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/PostBuilder.swift
1
6148
import Foundation @testable import WordPress /// Builds a Post /// /// Defaults to creating a post in a self-hosted site. class PostBuilder { private let post: Post init(_ context: NSManagedObjectContext = PostBuilder.setUpInMemoryManagedObjectContext(), blog: Blog? = nil) { post = NSEntityDescription.insertNewObject(forEntityName: Post.entityName(), into: context) as! Post // Non-null Core Data properties post.blog = blog ?? BlogBuilder(context).build() } private static func buildPost(context: NSManagedObjectContext) -> Post { let blog = NSEntityDescription.insertNewObject(forEntityName: Blog.entityName(), into: context) as! Blog blog.xmlrpc = "http://example.com/xmlrpc.php" blog.url = "http://example.com" blog.username = "test" blog.password = "test" let post = NSEntityDescription.insertNewObject(forEntityName: Post.entityName(), into: context) as! Post post.blog = blog return post } func published() -> PostBuilder { post.status = .publish return self } func drafted() -> PostBuilder { post.status = .draft return self } func scheduled() -> PostBuilder { post.status = .scheduled return self } func trashed() -> PostBuilder { post.status = .trash return self } func `private`() -> PostBuilder { post.status = .publishPrivate return self } func pending() -> PostBuilder { post.status = .pending return self } func revision() -> PostBuilder { post.setPrimitiveValue(post, forKey: "original") return self } func autosaved() -> PostBuilder { post.autosaveTitle = "a" post.autosaveExcerpt = "b" post.autosaveContent = "c" post.autosaveModifiedDate = Date() post.autosaveIdentifier = 1 return self } func withImage() -> PostBuilder { post.pathForDisplayImage = "https://localhost/image.png" return self } func with(status: BasePost.Status) -> PostBuilder { post.status = status return self } func with(pathForDisplayImage: String) -> PostBuilder { post.pathForDisplayImage = pathForDisplayImage return self } func with(title: String) -> PostBuilder { post.postTitle = title return self } func with(snippet: String) -> PostBuilder { post.content = snippet return self } func with(dateCreated: Date) -> PostBuilder { post.dateCreated = dateCreated return self } func with(dateModified: Date) -> PostBuilder { post.dateModified = dateModified return self } func with(author: String) -> PostBuilder { post.author = author return self } func with(userName: String) -> PostBuilder { post.blog.username = userName return self } func with(password: String) -> PostBuilder { post.blog.password = password return self } func with(remoteStatus: AbstractPostRemoteStatus) -> PostBuilder { post.remoteStatus = remoteStatus return self } func with(statusAfterSync: BasePost.Status?) -> PostBuilder { post.statusAfterSync = statusAfterSync return self } func with(image: String, status: MediaRemoteStatus? = nil, autoUploadFailureCount: Int = 0) -> PostBuilder { guard let context = post.managedObjectContext else { return self } guard let media = NSEntityDescription.insertNewObject(forEntityName: Media.entityName(), into: context) as? Media else { return self } media.localURL = image media.localThumbnailURL = "thumb-\(image)" media.blog = post.blog media.autoUploadFailureCount = NSNumber(value: autoUploadFailureCount) if let status = status { media.remoteStatus = status } media.addPostsObject(post) post.addMediaObject(media) return self } func with(media: [Media]) -> PostBuilder { for item in media { item.blog = post.blog } post.media = Set(media) return self } func with(autoUploadAttemptsCount: Int) -> PostBuilder { post.autoUploadAttemptsCount = NSNumber(value: autoUploadAttemptsCount) return self } func `is`(sticked: Bool) -> PostBuilder { post.isStickyPost = sticked return self } func supportsWPComAPI() -> PostBuilder { post.blog.supportsWPComAPI() return self } func confirmedAutoUpload() -> PostBuilder { post.shouldAttemptAutoUpload = true return self } /// Sets a random postID to emulate that self exists in the server. func withRemote() -> PostBuilder { post.postID = NSNumber(value: arc4random_uniform(UINT32_MAX)) return self } func cancelledAutoUpload() -> PostBuilder { post.shouldAttemptAutoUpload = false return self } func build() -> Post { // TODO: Enable this assertion once we can ensure that the post's MOC isn't being deallocated after the `PostBuilder` is // assert(post.managedObjectContext != nil) return post } static func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext { let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])! let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) do { try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) } catch { print("Adding in-memory persistent store failed") } let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator return managedObjectContext } }
gpl-2.0
3bb57508ebcbe99e27ba220892ca003e
26.693694
137
0.630937
5.076796
false
false
false
false
JeanVinge/UICollectionViewToolsSwift
UICollectionViewToolsSwift/Source/UITableView+Extension.swift
1
1903
// // UITableView+Extension.swift // Catalyst // // Created by Jean Vinge on 05/05/16. // Copyright © 2016 Atlas Politico. All rights reserved. // import UIKit extension UITableView { func dequeueReusableCell<T: UITableViewCell>(withCellClassType cellType: T.Type, atIndexPath indexPath: IndexPath) -> T { guard let cell = self.dequeueReusableCell(withIdentifier: cellType.className, for: indexPath) as? T else { fatalError("can't instantiate cell") } return cell } func dequeReusableCell<T: UITableViewCell>(withCellClassType cellType: T.Type) -> T { guard let cell = self.dequeueReusableCell(withIdentifier: cellType.className) as? T else { fatalError("can't instantiate cell") } return cell } func cell<T: UITableViewCell>(_ cellType: T.Type, atIndexPath indexPath: IndexPath, object: AnyObject?) -> T { let cell = dequeueReusableCell(withCellClassType: cellType, atIndexPath: indexPath) cell.configure(atIndexPath: indexPath, withObject: object) return cell } func initCell<T: UITableViewCell>(_ cellClass: T.Type, object: AnyObject?) -> T { let cell = dequeReusableCell(withCellClassType: cellClass) cell.configure(withObject: object) return cell } func registerNib<T: UITableViewCell>(_ cellClass: T.Type) { self.register(UINib(nibName: cellClass.className, bundle: nil), forCellReuseIdentifier: cellClass.className) } func cellForItemAtIndexPath<T: UITableViewCell>(_ cellClass: T.Type, atIndexPath indexPath: IndexPath) -> T { guard let cell = self.cellForRow(at: indexPath) as? T else { fatalError("Could not instantiate cell") } return cell } }
mit
1531a5b51bfdf683c9a88c94666c4780
30.7
125
0.633018
4.966057
false
false
false
false
raxcat/BufferSlider
Pod/Classes/BufferSlider.swift
1
6820
// // BufferSlider.swift // Pods // // Created by brianliu on 2016/2/22. // // import UIKit let padding:CGFloat = 0; ///Enum of vertical position public enum VerticalPosition:Int{ case top = 1 case center = 2 case bottom = 3 } /// - Easily use /// - Easily customize /// - Drop-In replacement /// - Supports **Objective-C** and **Swift** /// - *@IBDesignable* class *BufferSlider* /// - *@IBInspectable* property *bufferStartValue* (*Swift.Double*) /// - 0.0 ~ 1.0 /// - *@IBInspectable* property *bufferEndValue* (*Swift.Double*) /// - 0.1 ~ 1.0 /// - *@IBInspectable* property *borderColor* (*UIKit.UIColor*) /// - *@IBInspectable* property *fillColor* (*UIKit.UIColor*) /// - *@IBInspectable* property *borderWidth* (*Swift.Double*) /// - *@IBInspectable* property *sliderHeight* (*Swift.Double*) @IBDesignable open class BufferSlider: UISlider { ///0.0 ~ 1.0. @IBInspectable @IBInspectable open var bufferStartValue:Double = 0{ didSet{ if bufferStartValue < 0.0 { bufferStartValue = 0 } if bufferStartValue > bufferEndValue { bufferStartValue = bufferEndValue } self.setNeedsDisplay() } } ///0.0 ~ 1.0. @IBInspectable @IBInspectable open var bufferEndValue:Double = 0{ didSet{ if bufferEndValue > 1.0 { bufferEndValue = 1 } if bufferEndValue < bufferStartValue{ bufferEndValue = bufferStartValue } self.setNeedsDisplay() } } ///baseColor property. @IBInspectable @IBInspectable open var baseColor:UIColor = UIColor.lightGray ///progressColor property. @IBInspectable @IBInspectable open var progressColor:UIColor? = nil ///bufferColor property. @IBInspectable @IBInspectable open var bufferColor:UIColor? = nil ///BorderWidth property. @IBInspectable @IBInspectable open var borderWidth: Double = 0.5{ didSet{ if borderWidth < 0.1 { borderWidth = 0.1 } self.setNeedsDisplay() } } ///Slider height property. @IBInspectable @IBInspectable open var sliderHeight: Double = 2 { didSet{ if sliderHeight < 1 { sliderHeight = 1 } } } ///Adaptor property. Stands for vertical position of slider. (Swift and Objective-C) /// - 1 -> Top /// - 2 -> Center /// - 3 -> Bottom @IBInspectable open var sliderPositionAdaptor:Int{ get { return sliderPosition.rawValue } set{ let r = abs(newValue) % 3 switch r { case 1: sliderPosition = .top case 2: sliderPosition = .center case 0: sliderPosition = .bottom default: sliderPosition = .center } } } ///Vertical position of slider. (Swift only) open var sliderPosition:VerticalPosition = .center ///Draw round corner or not @IBInspectable open var roundedSlider:Bool = true ///Draw hollow or solid color @IBInspectable open var hollow:Bool = true ///Do not call this delegate mehtod directly. This is for hiding built-in slider drawing after iOS 7.0 open override func trackRect(forBounds bounds: CGRect) -> CGRect { var result = super.trackRect(forBounds: bounds) result.size.height = 0.01 return result } ///Custom Drawing. Subclass and and override to suit you needs. open override func draw(_ rect: CGRect) { // UIColor.redColor().colorWithAlphaComponent(0.3).set() // UIRectFrame(rect) baseColor.set() let rect = self.bounds.insetBy(dx: CGFloat(borderWidth)+padding, dy: CGFloat(borderWidth)) let height = sliderHeight.CGFloatValue let radius = height/2 var sliderRect = CGRect(x: rect.origin.x, y: rect.origin.y + (rect.height/2-radius), width: rect.width, height: rect.width) //default center switch sliderPosition { case .top: sliderRect.origin.y = rect.origin.y case .bottom: sliderRect.origin.y = rect.origin.y + rect.height - sliderRect.height default: break } let path = UIBezierPath() if roundedSlider { path.addArc(withCenter: CGPoint(x: sliderRect.minX + radius, y: sliderRect.minY+radius), radius: radius, startAngle: CGFloat(M_PI)/2, endAngle: -CGFloat(M_PI)/2, clockwise: true) path.addLine(to: CGPoint(x: sliderRect.maxX-radius, y: sliderRect.minY)) path.addArc(withCenter: CGPoint(x: sliderRect.maxX-radius, y: sliderRect.minY+radius), radius: radius, startAngle: -CGFloat(M_PI)/2, endAngle: CGFloat(M_PI)/2, clockwise: true) path.addLine(to: CGPoint(x: sliderRect.minX + radius, y: sliderRect.minY+height)) }else{ path.move(to: CGPoint(x: sliderRect.minX, y: sliderRect.minY+height)) path.addLine(to: sliderRect.origin) path.addLine(to: CGPoint(x: sliderRect.maxX, y: sliderRect.minY)) path.addLine(to: CGPoint(x: sliderRect.maxX, y: sliderRect.minY+height)) path.addLine(to: CGPoint(x: sliderRect.minX, y: sliderRect.minY+height)) } baseColor.setStroke() path.lineWidth = borderWidth.CGFloatValue path.stroke() if !hollow { path.fill() } path.addClip() var fillHeight = sliderRect.size.height-borderWidth.CGFloatValue if fillHeight < 0 { fillHeight = 0 } let fillRect = CGRect( x: sliderRect.origin.x + sliderRect.size.width*CGFloat(bufferStartValue), y: sliderRect.origin.y + borderWidth.CGFloatValue/2, width: sliderRect.size.width*CGFloat(bufferEndValue-bufferStartValue), height: fillHeight) if let color = bufferColor { color.setFill() } else if let color = self.superview?.tintColor{ color.setFill()} else{ UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0).setFill() } UIBezierPath(rect: fillRect).fill() if let color = progressColor{ color.setFill() let fillRect = CGRect( x: sliderRect.origin.x, y: sliderRect.origin.y + borderWidth.CGFloatValue/2, width: sliderRect.size.width*CGFloat((value-minimumValue)/(maximumValue-minimumValue)), height: fillHeight) UIBezierPath(rect: fillRect).fill() } } } extension Double{ var CGFloatValue: CGFloat { return CGFloat(self) } }
mit
c5abaf4ebd43eb4674b6831d99249237
33.795918
190
0.593548
4.275862
false
false
false
false
git-hushuai/MOMO
MMHSMeterialProject/UINavigationController/BusinessFile/数据缓存Item/TKResumeDataCacheTool.swift
1
9663
// // TKResumeDataCacheTool.swift // MMHSMeterialProject // // Created by hushuaike on 16/4/7. // Copyright © 2016年 hushuaike. All rights reserved. // import UIKit class TKResumeDataCacheTool: SQLTable { var id = -1; var ts = ""; var urlstr = ""; var userIdStr = ""; var key1 = ""; var key2 = ""; var key3 = ""; var cateGory = ""; var cityCateGory = ""; var logo = ""; var order_id = ""; var expected_job = ""; var sex = "" var position = "" var year_work = "" var name = "" var phone = ""; var email = ""; var recommend_reason = ""; var read_status = "" var content = "" var job = "" var update_time = "" var expected_position = ""; var resume_msg = "" var job_id = "" var resume_type = "" var app_pass_time = "" var degree = "" var cellItemInfo = "" init(){ let cachePaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) let cachePath = cachePaths[0] ; print("cache path :\(cachePath)"); super.init(tableName: "t_jobItems"); } required convenience init(tableName: String) { self.init(); } // 将表中某一类别的数据删除 func clearTableResumeInfoWithParms(cateGoryInfo:String,cityCateInfo:String)->CInt{ let deleRes = SQLiteDB.sharedInstance().execute("DELETE FROM t_jobItems WHERE cateGory = ? and cityCateGory = ? and userIdStr = ?;", parameters: [cateGoryInfo,cityCateInfo,GNUserService.sharedUserService().userId]); print("delete result info:\(deleRes)"); return deleRes; } // 清空表中所有数据 func clearTableAllResumeInfo()->CInt{ let deleRes = SQLiteDB.sharedInstance().execute("DELETE FROM t_jobItems;"); print("delete result info:\(deleRes)"); return deleRes; } // 判断简历在本地是否已经存在 func checkResumeItemIsAlreadySaveInLocal(urlstrInfo:String,resumeItemInfo:String)->[[String:AnyObject]]{ let cellItemCateInfo = self.getUserSelectCityName(); let queryData = SQLiteDB.sharedInstance().query("SELECT * FROM t_jobItems WHERE urlstr= ? AND userIdStr = ? AND cateGory = ? AND cityCateGory = ?;", parameters: [urlstrInfo,GNUserService.sharedUserService().userId,resumeItemInfo,cellItemCateInfo]); print("queryData inf0 :\(queryData)"); return queryData; } // 将本地缓存数据取出 func loadLocalAllResumeInfoWithResumeCateInfo(resumeItemInfo:String,timeStampInfo:String)->[[String:AnyObject]]{ let cellItemCateInfo = self.getUserSelectCityName(); let queryData = SQLiteDB.sharedInstance().query("SELECT * FROM t_jobItems WHERE userIdStr = ? AND cateGory = ? AND cityCateGory = ? And ts < ? order by ts desc limit 20", parameters: [GNUserService.sharedUserService().userId,resumeItemInfo,cellItemCateInfo,timeStampInfo]); print("queryData inf0 :\(queryData)"); return queryData; } // 保存一条简历数据 func setDBItemInfoWithResumeModel(resumeModel:TKJobItemModel){ print("save resume iteminfo :\(resumeModel)"); self.ts = (resumeModel.ts.intValue > 0) ? String.init(format: "%@", (resumeModel.ts)!) : ""; self.urlstr = (resumeModel.id.intValue > 0) ? String.init(format: "%@", resumeModel.id) : ""; self.userIdStr = GNUserService.sharedUserService().userId; self.cateGory = resumeModel.cellItemInfo != nil ? resumeModel.cellItemInfo : ""; self.cityCateGory = self.getUserSelectCityName(); self.logo = resumeModel.logo; print("self orderself info :\(resumeModel.order_id)"); let tempOrderInfo = GNUserService.sharedUserService().swiftTransportInfo(resumeModel.order_id); print("temp orderinfo :\(tempOrderInfo)"); if tempOrderInfo == "(null)"{ print("order_id 是空值"); resumeModel.order_id = NSNumber.init(int: -1); } self.order_id = resumeModel.order_id!.intValue>0 ? String.init(format: "%@", resumeModel.order_id!) : ""; self.expected_job = resumeModel.expected_job != nil ? (resumeModel.expected_job) : ""; if resumeModel.sex.intValue == -1{ self.sex = "暂无"; }else if (resumeModel.sex.intValue == 0){ self.sex = "男"; }else{ self.sex = "女"; } self.position = resumeModel.position != nil ? resumeModel.position : ""; self.year_work = resumeModel.year_work.intValue>0 ? String.init(format: "%@", (resumeModel.year_work)) : ""; self.name = resumeModel.name != nil ? (resumeModel.name) : ""; self.phone = resumeModel.phone.intValue>0 ? String.init(format: "%@", (resumeModel.phone)) : ""; self.email = resumeModel.email != nil ? (resumeModel.email) : ""; self.recommend_reason = resumeModel.recommend_reason != nil ? (resumeModel.recommend_reason) : ""; self.read_status = resumeModel.read_status != nil ? String.init(format: "%@", (resumeModel.read_status)) : ""; self.content = resumeModel.content != nil ? (resumeModel.content) : ""; self.job = resumeModel.job != nil ? (resumeModel.job) : ""; self.update_time = resumeModel.update_time != nil ? (resumeModel.update_time) : ""; self.expected_position = resumeModel.expected_position != nil ? (resumeModel.expected_position) : ""; self.resume_msg = resumeModel.resume_msg != nil ? (resumeModel.resume_msg) : ""; self.job_id = resumeModel.id != nil ? String.init(format: "%@", (resumeModel.id)) : ""; self.resume_type = resumeModel.resume_type != nil ? String.init(format: "%@", (resumeModel.resume_type)) : ""; self.app_pass_time = resumeModel.app_pass_time != nil ? (resumeModel.app_pass_time) : ""; self.degree = resumeModel.degree != nil ? (resumeModel.degree) : ""; self.cellItemInfo = resumeModel.cellItemInfo; } // var db : FMDatabase = FMDatabase.init(); // var dataBaseQ : FMDatabaseQueue = FMDatabaseQueue.init(); // // static let shareInstance = TKResumeDataCacheTool(); // private override init() { // // let cachePaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, // NSSearchPathDomainMask.UserDomainMask, true) // var cachePath = cachePaths[0] ; // //Cache目录-方法2 // let cachePath2 = NSHomeDirectory() + "/Library/Caches/data.db"; // // cachePath = cachePath + "/data.db" // // print("table DB cache :\(cachePath2)--cache:\(cachePath)"); // //if (NSFileManager.defaultManager().fileExistsAtPath(cachePath)){ // db = FMDatabase.init(path: cachePath); // dataBaseQ = FMDatabaseQueue.init(path: cachePath); // db.open(); // // } // // let result = db.executeUpdate("create table if not exists t_jobItems (id integer primary key autoincrement,ts text,urlstr text,userIdStr text,key1 text,key2 text,key3 text,cateGory text,cityCateGory text,logo text,order_id text,expected_job text,sex text,position text,year_work text,name text,phone text,email text,recommend_reason text,read_status text,content text,job text,update_time text,expected_position text,resume_msg text,job_id text,resume_type text,app_pass_time text,degree text,cellItemInfo text);", withArgumentsInArray: nil); // // if result == true { // print("创建成功"); // }else{ // print("创建失败"); // } // } // func getUserSelectCityName()->String{ var cityInfo = NSUserDefaults.standardUserDefaults().stringForKey("kUserDidSelectCityInfoKey"); if( cityInfo == nil) { cityInfo = "广州"; } return cityInfo as String!; } // // // // func saveWithResumeItemInfo(resumeModelInfo:TKJobItemModel)->Bool { // //// var copor : Bool = false; //// self.dataBaseQ.inDatabase { (db :FMDatabase!) -> Void in //// db.open(); //// let resumeDict = resumeModelInfo.toDict(); //// //// print("resume save dict info:\(resumeDict)"); //// //// let resumeData = NSKeyedArchiver.archivedDataWithRootObject(<#T##rootObject: AnyObject##AnyObject#>) //// //// //let resumeData = try? NSJSONSerialization.dataWithJSONObject(resumeDict as! AnyObject, options:NSJSONWritingOptions.PrettyPrinted) as NSData; //// //// let cityInfo = self.getUserSelectCityName(); //// //// let sql = "insert into t_jobItems (xgtsstr,urlstr,uesrIdStr,dict,cateGory,cityCateGory) values(?,?,?,?,?,?)"; //// //// copor = self.db.executeUpdate(sql, withArgumentsInArray: [resumeModelInfo.ts,resumeModelInfo.id,GNUserService.sharedUserService().userId,resumeData,resumeModelInfo.cellItemInfo,cityInfo]); //// //// if copor == true{ //// print("插入成功"); //// }else{ //// print("插入失败") //// } //// db.close(); //// } //// // return true; // } // }
mit
89da54fe79290bf571aed07dc5c0663b
38.256198
552
0.593368
4.153913
false
false
false
false
JohnEstropia/JEToolkit
JEToolkit/JEToolkit/Categories/NSDate+JEToolkit.swift
1
1468
// // NSDate+JEToolkit.swift // JEToolkit // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs === rhs || lhs.compare(rhs as Date) == .orderedSame } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs as Date) == .orderedAscending } extension NSDate: Comparable { }
mit
fae8d97045cc866a0c03fb3b06eb7b94
39.777778
82
0.732289
4.15864
false
false
false
false
narner/AudioKit
Examples/iOS/SongProcessor/SongProcessor/View Controllers/EffectsViewController.swift
1
1429
// // EffectsViewController.swift // SongProcessor // // Created by Elizabeth Simonian on 10/8/16. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit import AudioKitUI import UIKit class EffectsViewController: UIViewController { @IBOutlet private var volumeSlider: AKSlider! var docController: UIDocumentInteractionController? let songProcessor = SongProcessor.sharedInstance override func viewDidLoad() { super.viewDidLoad() AKStylist.sharedInstance.theme = .basic volumeSlider.range = 0 ... 10.0 volumeSlider.value = songProcessor.playerBooster.gain volumeSlider.callback = updateVolume navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(share(barButton:))) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateVolume(value: Double) { songProcessor.playerBooster.gain = value } @objc func share(barButton: UIBarButtonItem) { renderAndShare { docController in guard let canOpen = docController?.presentOpenInMenu(from: barButton, animated: true) else { return } if !canOpen { self.present(self.alertForShareFail(), animated: true, completion: nil) } } } }
mit
d5d65568758a377bf4b7d379cb4ee34c
27
142
0.682073
4.907216
false
false
false
false
wireapp/wire-ios-data-model
Source/Notifications/ObjectObserverTokens/MessageChangeInfo.swift
1
9127
// // Wire // Copyright (C) 2016 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 private var zmLog = ZMSLog(tag: "MessageChangeInfo") // MARK: Message observing enum MessageKey: String { case previewGenericMessage case mediumGenericMessage case linkPreview case underlyingMessage } extension ZMMessage: ObjectInSnapshot { @objc public class var observableKeys: Set<String> { return [#keyPath(ZMMessage.deliveryState), #keyPath(ZMMessage.isObfuscated)] } public var notificationName: Notification.Name { return .MessageChange } } extension ZMAssetClientMessage { public class override var observableKeys: Set<String> { let keys = super.observableKeys let additionalKeys = [#keyPath(ZMAssetClientMessage.transferState), MessageKey.previewGenericMessage.rawValue, MessageKey.mediumGenericMessage.rawValue, #keyPath(ZMAssetClientMessage.hasDownloadedPreview), #keyPath(ZMAssetClientMessage.hasDownloadedFile), #keyPath(ZMAssetClientMessage.isDownloading), #keyPath(ZMAssetClientMessage.progress), #keyPath(ZMMessage.reactions), #keyPath(ZMMessage.confirmations)] return keys.union(additionalKeys) } } extension ZMClientMessage { public class override var observableKeys: Set<String> { let keys = super.observableKeys let additionalKeys = [#keyPath(ZMAssetClientMessage.hasDownloadedPreview), #keyPath(ZMClientMessage.linkPreviewState), MessageKey.underlyingMessage.rawValue, #keyPath(ZMMessage.reactions), #keyPath(ZMMessage.confirmations), #keyPath(ZMClientMessage.quote), MessageKey.linkPreview.rawValue, #keyPath(ZMMessage.linkAttachments), #keyPath(ZMClientMessage.buttonStates)] return keys.union(additionalKeys) } } extension ZMImageMessage { public class override var observableKeys: Set<String> { let keys = super.observableKeys let additionalKeys = [#keyPath(ZMImageMessage.mediumData), #keyPath(ZMImageMessage.mediumRemoteIdentifier), #keyPath(ZMMessage.reactions)] return keys.union(additionalKeys) } } extension ZMSystemMessage { public class override var observableKeys: Set<String> { let keys = super.observableKeys let additionalKeys = [#keyPath(ZMSystemMessage.childMessages), #keyPath(ZMSystemMessage.systemMessageType)] return keys.union(additionalKeys) } } @objcMembers final public class MessageChangeInfo: ObjectChangeInfo { static let UserChangeInfoKey = "userChanges" static let ReactionChangeInfoKey = "reactionChanges" static let ButtonStateChangeInfoKey = "buttonStateChanges" static func changeInfo(for message: ZMMessage, changes: Changes) -> MessageChangeInfo? { return MessageChangeInfo(object: message, changes: changes) } public required init(object: NSObject) { self.message = object as! ZMMessage super.init(object: object) } public override var debugDescription: String { return ["deliveryStateChanged: \(deliveryStateChanged)", "reactionsChanged: \(reactionsChanged)", "confirmationsChanged: \(confirmationsChanged)", "childMessagesChanged: \(childMessagesChanged)", "quoteChanged: \(quoteChanged)", "imageChanged: \(imageChanged)", "fileAvailabilityChanged: \(fileAvailabilityChanged)", "usersChanged: \(usersChanged)", "linkPreviewChanged: \(linkPreviewChanged)", "transferStateChanged: \(transferStateChanged)", "senderChanged: \(senderChanged)", "isObfuscatedChanged: \(isObfuscatedChanged)", "underlyingMessageChanged: \(underlyingMessageChanged)", "linkAttachmentsChanged: \(linkAttachmentsChanged)", "buttonStatesChanged: \(buttonStatesChanged)" ].joined(separator: ", ") } public var deliveryStateChanged: Bool { return changedKeysContain(keys: #keyPath(ZMMessage.deliveryState)) } public var reactionsChanged: Bool { return changedKeysContain(keys: #keyPath(ZMMessage.reactions)) || changeInfos[MessageChangeInfo.ReactionChangeInfoKey] != nil } public var confirmationsChanged: Bool { return changedKeysContain(keys: #keyPath(ZMMessage.confirmations)) } public var underlyingMessageChanged: Bool { return changedKeysContain(keys: MessageKey.underlyingMessage.rawValue) } public var childMessagesChanged: Bool { return changedKeysContain(keys: #keyPath(ZMSystemMessage.childMessages)) } public var quoteChanged: Bool { return changedKeysContain(keys: #keyPath(ZMClientMessage.quote)) } /// Whether the image data on disk changed public var imageChanged: Bool { return changedKeysContain(keys: #keyPath(ZMImageMessage.mediumData), #keyPath(ZMImageMessage.mediumRemoteIdentifier), #keyPath(ZMAssetClientMessage.hasDownloadedPreview), #keyPath(ZMAssetClientMessage.hasDownloadedFile), MessageKey.previewGenericMessage.rawValue, MessageKey.mediumGenericMessage.rawValue) } /// Whether the file on disk changed public var fileAvailabilityChanged: Bool { return changedKeysContain(keys: #keyPath(ZMAssetClientMessage.hasDownloadedFile)) } public var usersChanged: Bool { return userChangeInfo != nil } public var linkPreviewChanged: Bool { return changedKeysContain(keys: #keyPath(ZMClientMessage.linkPreviewState), MessageKey.linkPreview.rawValue) } public var transferStateChanged: Bool { return changedKeysContain(keys: #keyPath(ZMAssetClientMessage.transferState)) } public var senderChanged: Bool { if self.usersChanged && (self.userChangeInfo?.user as? ZMUser == self.message.sender) { return true } return false } public var isObfuscatedChanged: Bool { return changedKeysContain(keys: #keyPath(ZMMessage.isObfuscated)) } public var linkAttachmentsChanged: Bool { return changedKeysContain(keys: #keyPath(ZMMessage.linkAttachments)) } public var buttonStatesChanged: Bool { return changedKeysContain(keys: #keyPath(ZMClientMessage.buttonStates)) || changeInfos[MessageChangeInfo.ButtonStateChangeInfoKey] != nil } public var userChangeInfo: UserChangeInfo? { return changeInfos[MessageChangeInfo.UserChangeInfoKey] as? UserChangeInfo } public let message: ZMMessage } @objc public protocol ZMMessageObserver: NSObjectProtocol { func messageDidChange(_ changeInfo: MessageChangeInfo) } extension MessageChangeInfo { /// Adds a ZMMessageObserver to the specified message /// To observe messages and their users (senders, systemMessage users), observe the conversation window instead /// Messages observed with this call will not contain information about user changes /// You must hold on to the token and use it to unregister @objc(addObserver:forMessage:managedObjectContext:) public static func add(observer: ZMMessageObserver, for message: ZMConversationMessage, managedObjectContext: NSManagedObjectContext) -> NSObjectProtocol { return ManagedObjectObserverToken(name: .MessageChange, managedObjectContext: managedObjectContext, object: message) { [weak observer] (note) in guard let `observer` = observer, let changeInfo = note.changeInfo as? MessageChangeInfo else { return } observer.messageDidChange(changeInfo) } } }
gpl-3.0
633d2a7d0ef2ad3f78484d08c55badf6
37.673729
145
0.651255
5.384661
false
false
false
false
looker-open-source/sdk-examples
swift/sample-swift-sdk/sample-swift-sdk/LookerSwiftSDK/transport.swift
3
9553
/* * The MIT License (MIT) * * Copyright (c) 2019 Looker Data Sciences, Inc. * * 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. */ /** A transport is a generic way to make HTTP requests. */ import Foundation let agentTag = "Swift-SDK \(Constants.sdkVersion)" /** * ResponseMode for an HTTP request - either binary or "string" */ enum ResponseMode { case binary, string, unknown } /** * MIME patterns for string content types * @type {RegExp} */ let contentPatternString = try? NSRegularExpression(Constants.matchModeString) /** * MIME patterns for "binary" content types * @type {RegExp} */ let contentPatternBinary = try? NSRegularExpression(Constants.matchModeBinary) /** * MIME pattern for UTF8 charset attribute * @type {RegExp} */ let charsetUtf8Pattern = try? NSRegularExpression(Constants.matchCharsetUtf8) let applicationJsonPattern = try? NSRegularExpression(Constants.applicationJson) /** * Default request timeout * @type {number} default request timeout is 120 seconds, or two minutes */ let defaultTimeout = 120 /** * Recognized HTTP methods */ enum HttpMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" case PATCH = "PATCH" case TRACE = "TRACE" case HEAD = "HEAD" } // TODO implement these stubs typealias Headers = Any typealias Agent = Any protocol ITransport { @available(OSX 10.15, *) func request<TSuccess: Codable, TError: Codable>( _ method: HttpMethod, _ path: String, _ queryParams: Values?, _ body: Any?, _ authenticator: Authenticator?, _ options: ITransportSettings? ) -> SDKResponse<TSuccess, TError> } /** A successful SDK call. */ protocol ISDKSuccessResponse { associatedtype T /** Whether the SDK call was successful. */ var ok: Bool { get set } // true /** The object returned by the SDK call. */ var value: T { get set } } /** An erroring SDK call. */ protocol ISDKErrorResponse { associatedtype T /** Whether the SDK call was successful. */ var ok: Bool { get set } // false /** The error object returned by the SDK call. */ var error: T { get set} } protocol ISDKError: LocalizedError { var message: String? { get set } var documentation_url: String? { get set } } /// Common ancestor for all error responses struct SDKError: ISDKError, Codable { var message : String? var documentation_url: String? private var reason: String? private var suggestion: String? private var help: String? init() { } init(_ message: String, documentation_url: String? = "", reason: String? = "", suggestion: String? = "", help: String? = "") { self.message = message self.reason = reason self.suggestion = suggestion self.help = help } /// A localized message describing the error var errorDescription: String? { get { return self.message } } /// A localized message describing the reason for the failure. var failureReason: String? { get { return self.reason } } /// A localized message describing how one might recover from the failure. var recoverySuggestion: String? { get { return self.suggestion } } /// A localized message providing "help" text if the user requests help. var helpAnchor: String? { get { return self.help } } } /// For deserializating JSON into SDK structures /// This could remain the same as simply `Codable`, but this abstraction is introduced for future extensibility protocol SDKModel: Codable { } enum SDKResponse<TSuccess, TError> where TError: ISDKError { case success(TSuccess) case error(TError) } func SDKOk(_ response: SDKResponse<Any, SDKError>) throws -> Any { switch response { case .success(let response): return response case .error(let error): throw SDKError(error.errorDescription ?? error.failureReason ?? error.recoverySuggestion ?? error.helpAnchor ?? "Unknown SDK Error") } } /** Generic http request property collection */ protocol IRequestInit { /** body of request. optional */ var body: Any? { get set } /** headers for request. optional */ var headers: StringDictionary<String>? { get set } /** Http method for request. required. */ var method: HttpMethod { get set } /** Redirect processing for request. optional */ var redirect: Any? { get set } /** http.Agent instance, allows custom proxy, certificate etc. */ var agent: Agent? { get set } /** support gzip/deflate content encoding. false to disable */ var compress: Bool? { get set } /** maximum redirect count. 0 to not follow redirect */ var follow: Int? { get set } /** maximum response body size in bytes. 0 to disable */ var size: Int? { get set } /** req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies) */ var timeout: Int? { get set } } typealias Authenticator = (_ req: URLRequest) -> URLRequest /** * Base authorization interface */ protocol IAuthorizer { var settings: IApiSettings { get set } var transport: ITransport { get set } /** is the current session authenticated? */ func isAuthenticated() -> Bool func authenticate(_ props: URLRequest) -> URLRequest func logout() -> Bool } /** General purpose authentication callback */ //protocol Authenticator { // func (init: Any) -> Any //} /** Interface for API transport values */ protocol ITransportSettings { /** base URL of host address */ var base_url: String? { get set } /** api version */ var api_version: String? { get set } /** standard headers to provide in all transport requests */ var headers: Headers? { get set } /** whether to verify ssl certs or not. Defaults to true */ var verify_ssl: Bool? { get set } /** request timeout in seconds. Default to 30 */ var timeout: Int? { get set } /** encoding override */ var encoding: String? { get set } } /// Returns `True` if `contentType` is charset utf-8 func isMimeUtf8(_ contentType: String) -> Bool { return charsetUtf8Pattern?.matches(contentType) ?? false } /// Returns `True` if `contentType` is JSON func isMimeJson(_ contentType: String) -> Bool { return applicationJsonPattern?.matches(contentType) ?? false } /// Is the content type binary or "string"? /// @param {String} contentType /// @returns {ResponseMode.binary | ResponseMode.string | ResponseMode.unknown} func responseMode(_ contentType: String) -> ResponseMode { if (contentPatternString!.matches(contentType)) { return ResponseMode.string } if (contentPatternBinary!.matches(contentType)) { return ResponseMode.binary } return ResponseMode.unknown } // Remove all "optional" possibly nil values from the dictionary func notAnOption(_ values: Values) -> ValueDictionary<String, Any> { var result = ValueDictionary<String, Any>() for (key, optional) in values { if let un = optional { result[key] = un } } return result } /** constructs the path argument including any optional query parameters @param path the base path of the request @param params optional collection of query parameters to encode and append to the path */ func addQueryParams(_ path: String, _ params: Values?) -> String { if (params == nil || params?.count == 0) { return path } var qp = "" if let up = params { // Strip out any values that may be assigned that are nil. let vals = notAnOption(up) qp = vals // TODO verify we don't need to filter out unset values // .filter { (key: String, value: Any) -> Bool in // guard value != nil { return true } else { return false } // } .map { (key: String, value: Any ) -> String in "\(key)=\(asQ(value))" } .joined(separator: "&") } var result = path if (qp != "") { result += "?" + qp } return result } //func sdkError(result: Any) -> Error { // if ("message" in result && typeof result.message === "string") { // return Error(result.message) // } // if ("error" in result && "message" in result.error && typeof result.error.message === "string") { // return Error(result.error.message) // } // let error = JSON.stringify(result) // return Error("Unknown error with SDK method \(error)") //}
mit
efb36bd0f2b2e468bce7bd331c86afb6
30.737542
130
0.658955
4.204665
false
false
false
false
lkzhao/Hero
Sources/Debug Plugin/HeroDebugPlugin.swift
1
6384
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <me@lkzhao.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(UIKit) && os(iOS) import UIKit public class HeroDebugPlugin: HeroPlugin { public static var showOnTop: Bool = false var debugView: HeroDebugView? var zPositionMap = [UIView: CGFloat]() var addedLayers: [CALayer] = [] var updating = false override public func animate(fromViews: [UIView], toViews: [UIView]) -> TimeInterval { if hero.forceNotInteractive { return 0 } var hasArc = false for v in context.fromViews + context.toViews where context[v]?.arc != nil && context[v]?.position != nil { hasArc = true break } let debugView = HeroDebugView(initialProcess: hero.isPresenting ? 0.0 : 1.0, showCurveButton: hasArc, showOnTop: HeroDebugPlugin.showOnTop) debugView.frame = hero.container.bounds debugView.delegate = self hero.container.window?.addSubview(debugView) debugView.layoutSubviews() self.debugView = debugView UIView.animate(withDuration: 0.4) { debugView.showControls = true } return .infinity } public override func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval { guard let debugView = debugView else { return 0.4 } debugView.delegate = nil UIView.animate(withDuration: 0.4) { debugView.showControls = false debugView.debugSlider.setValue(roundf(debugView.progress), animated: true) } on3D(wants3D: false) return 0.4 } public override func clean() { debugView?.removeFromSuperview() debugView = nil } } extension HeroDebugPlugin: HeroDebugViewDelegate { public func onDone() { guard let debugView = debugView else { return } let seekValue = hero.isPresenting ? debugView.progress : 1.0 - debugView.progress if seekValue > 0.5 { hero.finish() } else { hero.cancel() } } public func onProcessSliderChanged(progress: Float) { let seekValue = hero.isPresenting ? progress : 1.0 - progress hero.update(CGFloat(seekValue)) } func onPerspectiveChanged(translation: CGPoint, rotation: CGFloat, scale: CGFloat) { var t = CATransform3DIdentity t.m34 = -1 / 4000 t = CATransform3DTranslate(t, translation.x, translation.y, 0) t = CATransform3DScale(t, scale, scale, 1) t = CATransform3DRotate(t, rotation, 0, 1, 0) hero.container.layer.sublayerTransform = t } func animateZPosition(view: UIView, to: CGFloat) { let a = CABasicAnimation(keyPath: "zPosition") a.fromValue = view.layer.value(forKeyPath: "zPosition") a.toValue = NSNumber(value: Double(to)) a.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) a.duration = 0.4 view.layer.add(a, forKey: "zPosition") view.layer.zPosition = to } func onDisplayArcCurve(wantsCurve: Bool) { for layer in addedLayers { layer.removeFromSuperlayer() addedLayers.removeAll() } if wantsCurve { for layer in hero.container.layer.sublayers! { for (_, anim) in layer.animations { if let keyframeAnim = anim as? CAKeyframeAnimation, let path = keyframeAnim.path { let s = CAShapeLayer() s.zPosition = layer.zPosition + 10 s.path = path s.strokeColor = UIColor.blue.cgColor s.fillColor = UIColor.clear.cgColor hero.container.layer.addSublayer(s) addedLayers.append(s) } } } } } func on3D(wants3D: Bool) { var t = CATransform3DIdentity if wants3D { var viewsWithZPosition = Set<UIView>() for view in hero.container.subviews where view.layer.zPosition != 0 { viewsWithZPosition.insert(view) zPositionMap[view] = view.layer.zPosition } let viewsWithoutZPosition = hero.container.subviews.filter { return !viewsWithZPosition.contains($0) } let viewsWithPositiveZPosition = viewsWithZPosition.filter { return $0.layer.zPosition > 0 } for (i, v) in viewsWithoutZPosition.enumerated() { animateZPosition(view: v, to: CGFloat(i * 10)) } var maxZPosition: CGFloat = 0 for v in viewsWithPositiveZPosition { maxZPosition = max(maxZPosition, v.layer.zPosition) animateZPosition(view: v, to: v.layer.zPosition + CGFloat(viewsWithoutZPosition.count * 10)) } t.m34 = -1 / 4000 t = CATransform3DTranslate(t, debugView!.translation.x, debugView!.translation.y, 0) t = CATransform3DScale(t, debugView!.scale, debugView!.scale, 1) t = CATransform3DRotate(t, debugView!.rotation, 0, 1, 0) } else { for v in hero.container.subviews { animateZPosition(view: v, to: self.zPositionMap[v] ?? 0) } self.zPositionMap.removeAll() } let a = CABasicAnimation(keyPath: "sublayerTransform") a.fromValue = hero.container.layer.value(forKeyPath: "sublayerTransform") a.toValue = NSValue(caTransform3D: t) a.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) a.duration = 0.4 UIView.animate(withDuration: 0.4) { self.context.container.backgroundColor = UIColor(white: 0.85, alpha: 1.0) } hero.container.layer.add(a, forKey: "debug") hero.container.layer.sublayerTransform = t } } #endif
mit
6ba980d6472e560556776dda8af42be3
34.270718
143
0.68938
4.140078
false
false
false
false
izotx/iTenWired-Swift
Conference App/FNBJSocialFeed/FNBJSocialFeedFacebookUser.swift
1
1124
// // FNBJSocialFeedFacebookUser.swift // FNBJSocialFeed // // Created by Felipe on 6/1/16. // Copyright © 2016 Academic Technology Center. All rights reserved. // import Foundation enum FNBJSocialFeedFacebookuserEnum : String{ case name case url case picture case data } class FNBJSocialFeedFacebookUser{ var profilePicture = "" // init(dictionary: NSDictionary){ // // if let name = dictionary.objectForKey(FNBJSocialFeedFacebookuserEnum.name.rawValue) as? String{ // self.name = name // } // // if let picture = dictionary.objectForKey(FNBJSocialFeedFacebookuserEnum.picture.rawValue) as? NSDictionary{ // // if let data = picture.objectForKey(FNBJSocialFeedFacebookuserEnum.data.rawValue) as? NSDictionary{ // // if let url = data.objectForKey(FNBJSocialFeedFacebookuserEnum.url.rawValue) as? String{ // print (url) // // self.profilePicture = url // } // } // // } // // } }
bsd-2-clause
08cf1c31614aafe94ca4c72e2c59875b
23.977778
117
0.58415
4.221805
false
false
false
false
phatblat/Quick
Sources/Quick/Callsite.swift
7
1544
import Foundation #if canImport(Darwin) @objcMembers public class _CallsiteBase: NSObject {} #else public class _CallsiteBase: NSObject {} #endif // Ideally we would always use `StaticString` as the type for tracking the file name // in which an example is defined, for consistency with `assert` etc. from the // stdlib, and because recent versions of the XCTest overlay require `StaticString` // when calling `XCTFail`. Under the Objective-C runtime (i.e. building on macOS), we // have to use `String` instead because StaticString can't be generated from Objective-C #if SWIFT_PACKAGE public typealias FileString = StaticString #else public typealias FileString = String #endif /** An object encapsulating the file and line number at which a particular example is defined. */ final public class Callsite: _CallsiteBase { /** The absolute path of the file in which an example is defined. */ public let file: FileString /** The line number on which an example is defined. */ public let line: UInt internal init(file: FileString, line: UInt) { self.file = file self.line = line } } extension Callsite { /** Returns a boolean indicating whether two Callsite objects are equal. If two callsites are in the same file and on the same line, they must be equal. */ @nonobjc public static func == (lhs: Callsite, rhs: Callsite) -> Bool { return String(describing: lhs.file) == String(describing: rhs.file) && lhs.line == rhs.line } }
apache-2.0
b5b34ed1781e78ce5bee5301d8706e37
29.88
99
0.697539
4.288889
false
false
false
false
calkinsc3/SwiftCustomSlider
CustomSliderExample/AppDelegate.swift
1
6198
// // AppDelegate.swift // CustomSliderExample // // Created by Calkins, Bill on 9/2/14. // Copyright (c) 2014 Calkins, Bill. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication!) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication!) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication!) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication!) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication!) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.amfam.CustomSliderExample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CustomSliderExample", withExtension: "momd") return NSManagedObjectModel(contentsOfURL: modelURL!) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CustomSliderExample.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
a4662f26b53c14a8451fdf0fef9f472e
54.837838
290
0.714747
5.819718
false
false
false
false
yangyueguang/MyCocoaPods
Extension/UIView+Extension.swift
1
9850
// // UIView+Extension.swift import UIKit import Foundation public extension UIView { var x: CGFloat { set { self.frame = CGRect(x: x, y: frame.origin.y, width: frame.size.width, height: frame.size.height) } get { return frame.origin.x } } var y: CGFloat { set { self.frame = CGRect(x: frame.origin.x, y: y, width: frame.size.width, height: frame.size.height) } get { return frame.origin.y } } var width: CGFloat { set { self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: width, height: frame.size.height) } get { return frame.size.width } } var height: CGFloat { set { self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: height) } get { return frame.size.height } } var right: CGFloat { get { return frame.origin.x + frame.size.width } set { self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: right - frame.origin.x, height: frame.size.height) } } var bottom: CGFloat { get { return frame.origin.y + frame.size.height } set { self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: bottom - frame.origin.y) } } var size: CGSize { set { self.frame.size = size } get { return frame.size } } func alignmentLeft(_ view: UIView, _ offset: CGFloat = 0) { self.frame = CGRect(x: view.x + offset, y: frame.origin.y, width: frame.size.width, height: frame.size.height) } func alignmentRight(_ view: UIView, _ offset: CGFloat = 0) { self.frame = CGRect(x: view.right - self.width + offset, y: frame.origin.y, width: frame.size.width, height: frame.size.height) } func alignmentTop(_ view: UIView, _ offset: CGFloat = 0) { self.frame = CGRect(x: frame.origin.x, y: view.y + offset, width: frame.size.width, height: frame.size.height) } func alignmentBottom(_ view: UIView, _ offset: CGFloat = 0) { self.frame = CGRect(x: frame.origin.x, y: view.bottom - frame.size.height + offset, width: frame.size.width, height: frame.size.height) } func alignmentHorizontal(_ view: UIView) { self.center = CGPoint(x: view.center.x, y: center.y) } func alignmentVertical(_ view: UIView) { self.center = CGPoint(x: center.x, y: view.center.y) } /// 变圆 func round() { layer.masksToBounds = true layer.cornerRadius = size.width / 2 } // MARK:- 裁剪圆角 func clipCorner(direction: UIRectCorner, radius: CGFloat) { let cornerSize = CGSize(width: radius, height: radius) let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize) let maskLayer = CAShapeLayer() maskLayer.frame = bounds maskLayer.path = maskPath.cgPath layer.addSublayer(maskLayer) layer.mask = maskLayer } /// 批量添加子视图 func addSubviews(_ views:[UIView]) { for v in views { self.addSubview(v) } } /// 添加点击响应 func add(_ target: AnyObject, action: Selector) { let tap = UITapGestureRecognizer(target: target, action: action) self.isUserInteractionEnabled = true self.addGestureRecognizer(tap) } /// 类似qq聊天窗口的抖动效果 func shakeAnimation() { let t: CGFloat = 5.0 let translateRight = CGAffineTransform.identity.translatedBy(x: t, y: 0.0) let translateLeft = CGAffineTransform.identity.translatedBy(x: -t, y: 0.0) let translateTop = CGAffineTransform.identity.translatedBy(x: 0.0, y: 1) let translateBottom = CGAffineTransform.identity.translatedBy(x: 0.0, y: -1) self.transform = translateLeft UIView.animate(withDuration: 0.07, delay: 0.0, options: .autoreverse, animations: { UIView.setAnimationRepeatCount(2.0) self.transform = translateRight }) { finished in UIView.animate(withDuration: 0.07, animations: { self.transform = translateBottom }) { finished in UIView.animate(withDuration: 0.07, animations: { self.transform = translateTop }) { finished in UIView.animate(withDuration: 0.05, delay: 0.0, options: .beginFromCurrentState, animations: { self.transform = .identity //回到没有设置transform之前的坐标 }) } } } } /// 左右抖动 func leftRightAnimation() { let t: CGFloat = 5.0 let translateRight = CGAffineTransform.identity.translatedBy(x: t, y: 0.0) let translateLeft = CGAffineTransform.identity.translatedBy(x: -t, y: 0.0) self.transform = translateLeft UIView.animate(withDuration: 0.07, delay: 0.0, options: [.autoreverse, .repeat], animations: { UIView.setAnimationRepeatCount(2.0) self.transform = translateRight }) { finished in if finished { UIView.animate(withDuration: 0.05, delay: 0.0, options: .beginFromCurrentState, animations: { self.transform = .identity }) } } } func imageFromView() -> UIImage? { UIGraphicsBeginImageContext(frame.size) let context = UIGraphicsGetCurrentContext() if let aContext = context { layer.render(in: aContext) } let theImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return theImage } func bestRoundCorner() { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: bounds.size) let layer = CAShapeLayer() layer.frame = bounds layer.path = path.cgPath self.layer.mask = layer } /// 是否包含视图类型或指定视图 func contains(_ subView: UIView?, typeClass: AnyClass?) -> Bool { for view in subviews { if let subView = subView { return view.isEqual(subView) } if let typeClass = typeClass { if type(of: view) === typeClass { return true } } } return false } func linearColorFromcolors(_ colors: [UIColor], isHorizantal hor: Bool = true) { if colors.count < 2 { backgroundColor = colors.first return } var cgColors: [CGColor] = [] var locations: [NSNumber] = [] let lenth: Float = 1.0 / Float(colors.count - 1) for i in 0..<colors.count { let loc = NSNumber(value: Float(i) * lenth) locations.append(loc) let color: UIColor = colors[i] cgColors.append(color.cgColor) } let gradientLayer = CAGradientLayer() gradientLayer.frame = bounds gradientLayer.colors = cgColors if hor { gradientLayer.startPoint = CGPoint(x: 0, y: 1) gradientLayer.endPoint = CGPoint(x: 1, y: 1) } else { gradientLayer.startPoint = CGPoint(x: 0, y: 1) gradientLayer.endPoint = CGPoint(x: 0, y: 0) } gradientLayer.locations = locations layer.addSublayer(gradientLayer) } func gotCircleLinear(fromColors colors: [UIColor]) -> UIImage? { let rect: CGRect = bounds var ra = CGAffineTransform(scaleX: 1, y: 1) let path = CGPath(rect: rect, transform: &ra) // 绘制渐变层 var cgColors = [AnyHashable](repeating: 0, count: colors.count) for co in colors { cgColors.append(co.cgColor) } UIGraphicsBeginImageContext(rect.size) let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = UIGraphicsGetCurrentContext(), let gradient = CGGradient(colorsSpace: colorSpace, colors: cgColors as CFArray, locations: nil) else { return nil} let pathRect: CGRect = path.boundingBox let center = CGPoint(x: pathRect.midX, y: pathRect.midY) let radius: CGFloat = max(pathRect.size.width / 2.0, pathRect.size.height / 2.0) * sqrt(2) context.saveGState() context.addPath(path) context.clip() context.drawRadialGradient(gradient, startCenter: center, startRadius: 0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions.drawsBeforeStartLocation) context.restoreGState() let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } func linearTextColor(fromSuperView bgView: UIView, colors: [UIColor]) { var cgColors: [CGColor] = [] for co in colors { cgColors.append(co.cgColor) } let gradientLayer1 = CAGradientLayer() gradientLayer1.frame = frame gradientLayer1.colors = cgColors gradientLayer1.startPoint = CGPoint(x: 0, y: 0) gradientLayer1.endPoint = CGPoint(x: 1, y: 0) bgView.layer.addSublayer(gradientLayer1) gradientLayer1.mask = layer frame = gradientLayer1.bounds } static func xibView() -> Self? { let nib = UINib(nibName: nameOfClass, bundle: Bundle.main) let view = nib.instantiate(withOwner: self, options: [:]).first as? UIView return view?.toType() } }
mit
209438f693683e44a55ac2179b1a8073
33.978417
179
0.585459
4.306466
false
false
false
false
shmidt/ContactsPro
ContactsPro/Helpers/Realm/Location.swift
1
4913
import UIKit import Realm import CoreLocation import MapKit import CloudKit import AddressBook import AddressBookUI class Location: RLMObject, MKAnnotation { dynamic var uuid = NSUUID().UUIDString dynamic var name = "" dynamic var note = "" dynamic var aptNo = "" dynamic var floorNo = "" dynamic var entranceNo = "" dynamic var houseNo = "" dynamic var street = "" dynamic var city = "" dynamic var province = "" dynamic var postalCode = "" dynamic var country:String = Location.currentCountry() // dynamic var type:Int = 0 dynamic var latitude = 0.0 dynamic var longitude = 0.0 class func currentCountry() -> String{ let locale = NSLocale.currentLocale() let countryCode = locale.objectForKey(NSLocaleCountryCode) as String return locale.displayNameForKey(NSLocaleCountryCode, value: countryCode) ?? ""//"RUSSIA"//TODO: } dynamic var distance: CLLocationDistance = 0 func ignoredProperties() -> NSArray { let propertiesToIgnore = [distance] return propertiesToIgnore } // func fill(placemark:GooglePlacemark) -> () { // name = placemark.name //// note = //// aptNo = //// floorNo = //// entranceNo = // houseNo = placemark.streetNumber // street = placemark.route // city = placemark.locality // province = placemark.administrativeArea // postalCode = placemark.postalCode // country = placemark.country //// //// //// placemark.subLocality //// placemark.formattedAddress //// //// placemark.administrativeAreaCode //// placemark.subAdministrativeArea //// //// //// placemark.ISOcountryCode //// placemark.state // // } var addressDictionary: [String: String]{ var addressDict = [ kABPersonAddressStreetKey as String : street, kABPersonAddressCityKey as String : city, kABPersonAddressStateKey as String : province, kABPersonAddressZIPKey as String : postalCode, kABPersonAddressCountryKey as String : country ] return addressDict } var summary:String{ get{ var addr = "" if !entranceNo.isEmpty{ addr += "entrance No." + " " + entranceNo + "\n" } if !floorNo.isEmpty{ addr += "floor No." + " " + floorNo + "\n" } if !aptNo.isEmpty{ addr += "apt. No." + " " + aptNo + "\n" } let textValues = [addr, street, city, province, postalCode, country] var text = "\n".join(textValues.filter( { $0.isEmpty == false } ).map({ $0 })) return text } } var addressString: String{ get{ return ABCreateStringWithAddressDictionary(addressDictionary, false) } } dynamic var location:CLLocation{ get{ return CLLocation(latitude: latitude, longitude: longitude) } set(newLocation){ latitude = newLocation.coordinate.latitude longitude = newLocation.coordinate.longitude } } override class func ignoredProperties() -> [AnyObject]! { return ["location", "coordinate"] } override class func primaryKey() -> String! { return "uuid" } // var record : CKRecord! { // didSet { // name = record.objectForKey("Name") as String! // location = record.objectForKey("Location") as CLLocation! // } // } // // dynamic var recordID: CKRecordID{ // get{ // CKRecordID(recordName: recordName) // } // set{ // // } // } // dynamic var recordName = "" // dynamic var category = Category() //MARK: - map annotation dynamic var coordinate : CLLocationCoordinate2D { get { return location.coordinate } set(newCoordinate){ latitude = newCoordinate.latitude longitude = newCoordinate.longitude } } var title : String! { get { return name } } // // 4 // let lat = aDecoder.decodeDoubleForKey("latitude") // let lon = aDecoder.decodeDoubleForKey("longitude") // // 5 // let decodedLocation = CLLocation(latitude: lat, // longitude: lon) // self.record.setObject(decodedLocation, forKey: "Location") // self.location = decodedLocation } //MARK: Equatable //func == (lhs: Location, rhs: Location) -> Bool { // return lhs.record.recordID == rhs.record.recordID //}
mit
1b06f0db06c02da21191fa6fc6edab92
28.957317
103
0.545695
4.7195
false
false
false
false
chrisbudro/ThisPic
ThisPic/Controller/CaptionsViewController.swift
1
1500
// // CaptionsViewController.swift // ParseStarterProject // // Created by Chris Budro on 8/10/15. // Copyright (c) 2015 Parse. All rights reserved. // import UIKit import Parse class CaptionsViewController: UIViewController { //MARK: Outlets @IBOutlet weak var shareButton: UIButton! @IBOutlet weak var captionTextView: UITextView! //MARK: Properties var shareAction: ((caption: String?) -> Void)? var captionText: String? //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() captionTextView.delegate = self if captionText == nil { captionTextView.textColor = UIColor.lightGrayColor() } } //MARK: Actions @IBAction func shareWasPressed(sender: AnyObject) { shareButton.enabled = false shareAction?(caption: captionText) } @IBAction func cancelWasPressed(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } } //MARK: Text View Delegate extension CaptionsViewController: UITextViewDelegate { func textViewDidBeginEditing(textView: UITextView) { textView.textColor = UIColor.blackColor() if captionText == nil { captionTextView.text = nil } } func textViewDidChange(textView: UITextView) { captionText = textView.text } func textViewDidEndEditing(textView: UITextView) { captionText = textView.text if textView.text == "" { textView.text = "Add a Caption..." textView.textColor = UIColor.lightGrayColor() } } }
mit
e63d68574d2991316502fb4708d13d51
22.809524
58
0.697333
4.464286
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationData/DIKit.swift
1
5693
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import FeatureAuthenticationDomain import NetworkKit import WalletPayloadKit extension DependencyContainer { // MARK: - FeatureAuthenticationData Module public static var featureAuthenticationData = module { // MARK: - WalletNetworkClients factory { AutoWalletPairingClient() as AutoWalletPairingClientAPI } factory { GuidClient() as GuidClientAPI } factory { SMSClient() as SMSClientAPI } factory { SessionTokenClient() as SessionTokenClientAPI } factory { TwoFAWalletClient() as TwoFAWalletClientAPI } factory { DeviceVerificationClient() as DeviceVerificationClientAPI } factory { PushNotificationsClient() as PushNotificationsClientAPI } factory { MobileAuthSyncClient() as MobileAuthSyncClientAPI } // MARK: - NabuNetworkClients factory { JWTClient() as JWTClientAPI } factory { NabuUserCreationClient() as NabuUserCreationClientAPI } factory { NabuSessionTokenClient() as NabuSessionTokenClientAPI } factory { NabuUserRecoveryClient() as NabuUserRecoveryClientAPI } factory { NabuResetUserClient() as NabuResetUserClientAPI } factory { NabuUserResidentialInfoClient() as NabuUserResidentialInfoClientAPI } // MARK: - AppStore factory { AppStoreInformationClient() as AppStoreInformationClientAPI } // MARK: - Repositories factory { JWTRepository() as JWTRepositoryAPI } factory { AccountRecoveryRepository() as AccountRecoveryRepositoryAPI } factory { DeviceVerificationRepository() as DeviceVerificationRepositoryAPI } factory { RemoteSessionTokenRepository() as RemoteSessionTokenRepositoryAPI } factory { RemoteGuidRepository() as RemoteGuidRepositoryAPI } factory { AutoWalletPairingRepository() as AutoWalletPairingRepositoryAPI } factory { TwoFAWalletRepository() as TwoFAWalletRepositoryAPI } factory { SMSRepository() as SMSRepositoryAPI } factory { MobileAuthSyncRepository() as MobileAuthSyncRepositoryAPI } factory { PushNotificationsRepository() as PushNotificationsRepositoryAPI } factory { AppStoreInformationRepository() as AppStoreInformationRepositoryAPI } // MARK: - Wallet Repositories factory { () -> AuthenticatorRepositoryAPI in let walletRepository: WalletRepositoryProvider = DIKit.resolve() return AuthenticatorRepository( walletRepository: walletRepository.repository, walletRepo: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } factory { () -> SharedKeyRepositoryAPI in let walletRepository: WalletRepositoryProvider = DIKit.resolve() return SharedKeyRepository( walletRepository: walletRepository.repository, walletRepo: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } factory { () -> SessionTokenRepositoryAPI in let walletRepository: WalletRepositoryProvider = DIKit.resolve() return SessionTokenRepository( walletRepository: walletRepository.repository, walletRepo: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } factory { () -> GuidRepositoryAPI in let walletRepository: WalletRepositoryProvider = DIKit.resolve() return GuidRepository( walletRepository: walletRepository.repository, walletRepo: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } factory { () -> PasswordRepositoryAPI in let walletRepository: WalletRepositoryProvider = DIKit.resolve() return PasswordRepository( walletRepository: walletRepository.repository, walletRepo: DIKit.resolve(), changePasswordService: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } factory { () -> CredentialsRepositoryAPI in let guidRepo: GuidRepositoryAPI = DIKit.resolve() let sharedKeyRepo: SharedKeyRepositoryAPI = DIKit.resolve() return CredentialsRepository( guidRepository: guidRepo, sharedKeyRepository: sharedKeyRepo ) } single { () -> NabuOfflineTokenRepositoryAPI in let repository: WalletRepositoryAPI = DIKit.resolve() return NabuOfflineTokenRepository( walletRepository: repository, credentialsFetcher: DIKit.resolve(), reactiveWallet: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } // MARK: - Nabu Authentication single { NabuTokenRepository() as NabuTokenRepositoryAPI } factory { NabuAuthenticator() as AuthenticatorAPI } factory { NabuRepository() as NabuRepositoryAPI } factory { () -> CheckAuthenticated in unauthenticated as CheckAuthenticated } } } private func unauthenticated( communicatorError: NetworkError ) -> AnyPublisher<Bool, Never> { guard let authenticationError = NabuAuthenticationError(error: communicatorError), case .tokenExpired = authenticationError else { return .just(false) } return .just(true) }
lgpl-3.0
52109c24c8a398d9ddaeb1e084733239
33.49697
87
0.658117
6.029661
false
false
false
false
kanekomasanori/photo_display
PhotoDisplay/PhotoCollectionViewController.swift
1
4009
// // PhotoCollectionViewController.swift // PhotoDisplay // // Created by Masanori.KANEKO on 2015/08/03. // Copyright (c) 2015年 Masanori.KANEKO. All rights reserved. // import UIKit import Photos let reuseIdentifier = "photoCell" protocol PhotoCollectionViewDelegate{ func seelctedImage(image: UIImage) } class PhotoCollectionViewController: UICollectionViewController { @IBOutlet var _collectionView: UICollectionView! var photoAssets = [PHAsset]() var delegate: PhotoCollectionViewDelegate! = nil internal func displayPhotos() { photoAssets = [] var assets: PHFetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: nil) assets.enumerateObjectsUsingBlock { (asset, index, stop) -> Void in self.photoAssets.append(asset as! PHAsset) } _collectionView.reloadData() } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return self.photoAssets.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> PhotoCollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PhotoCollectionViewCell let printManager: PHImageManager = PHImageManager() PHImageManager.defaultManager().requestImageDataForAsset(photoAssets[indexPath.row], options: nil, resultHandler: {(imageData: NSData!, dataUTI: String!, orientation: UIImageOrientation, info: [NSObject : AnyObject]!) in cell.photoImageData = imageData }) // Configure the cell return cell } // MARK: UICollectionViewDelegate // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { collectionView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .CenteredVertically) var collectionViewCell:PhotoCollectionViewCell = (collectionView.cellForItemAtIndexPath(indexPath) as? PhotoCollectionViewCell)! var selectedPhotoImageView:UIImageView = collectionViewCell.photoImageView var selectedPhotoImage:UIImage = selectedPhotoImageView.image! delegate.seelctedImage(selectedPhotoImage) return true } }
mit
ea5d2712cf0cdbee6a97762ba7ce5ecc
38.673267
228
0.730472
5.936296
false
false
false
false
abiaoLHB/LHBWeiBo-Swift
LHBWeibo/LHBWeibo/MainWibo/Tools/Emoticon/Model/Emoticon.swift
1
1781
// // Emoticon.swift // 到处enmoci // // Created by LHB on 16/8/30. // Copyright © 2016年 LHB. All rights reserved. // import UIKit class Emoticon: NSObject { // MARK:- 定义属性 var code : String? { // emoji的code didSet { guard let code = code else { return } // 1.创建扫描器 let scanner = NSScanner(string: code) // 2.调用方法,扫描出code中的值 var value : UInt32 = 0 scanner.scanHexInt(&value) // 3.将value转成字符 let c = Character(UnicodeScalar(value)) // 4.将字符转成字符串 emojiCode = String(c) } } var png : String? { // 普通表情对应的图片名称 didSet { guard let png = png else { return } pngPath = NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + png } } var chs : String? // 普通表情对应的文字 // MARK:- 数据处理 var pngPath : String? var emojiCode : String? var isRemove : Bool = false var isEmpty : Bool = false // MARK:- 自定义构造函数 init(dict : [String : String]) { super.init() setValuesForKeysWithDictionary(dict) } init (isRemove : Bool) { self.isRemove = isRemove } init (isEmpty : Bool) { self.isEmpty = isEmpty } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} override var description : String { return dictionaryWithValuesForKeys(["emojiCode", "pngPath", "chs"]).description } }
apache-2.0
a7a021e02167e7f70881345e2b55fccd
22.855072
87
0.5
4.546961
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Mesh/StepGetWifiNetwork.swift
1
1727
// // Created by Raimundas Sakalauskas on 2019-03-04. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation class StepGetWifiNetwork: Gen3SetupStep { private var wifiNetworkInfoLoaded = false override func reset() { wifiNetworkInfoLoaded = false } override func start() { guard let context = self.context else { return } if (!wifiNetworkInfoLoaded) { self.getTargetDeviceWifiNetworkInfo() } else { self.stepCompleted() } } private func getTargetDeviceWifiNetworkInfo() { context?.targetDevice.transceiver?.sendGetCurrentWifiNetwork { [weak self, weak context] result, networkInfo in guard let self = self, let context = context, !context.canceled else { return } self.log("targetDevice.sendGetCurrentWifiNetwork: \(result.description())") self.log("\(networkInfo as Optional)"); if (result == .NOT_FOUND || result == .INVALID_STATE) { self.wifiNetworkInfoLoaded = true context.targetDevice.wifiNetworkInfo = nil self.start() } else if (result == .NONE) { self.wifiNetworkInfoLoaded = true context.targetDevice.wifiNetworkInfo = networkInfo self.start() } else { self.handleBluetoothErrorResult(result) } } } override func rewindTo(context: Gen3SetupContext) { super.rewindTo(context: context) guard let context = self.context else { return } context.targetDevice.wifiNetworkInfo = nil } }
apache-2.0
c31ac13dca72801eb4729d8c000c7a65
26.854839
119
0.585987
5.094395
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/HomePage/View/ZHNhomePageCoinCell.swift
1
1779
// // ZHNhomePageCoinCell.swift // zhnbilibili // // Created by 张辉男 on 17/1/14. // Copyright © 2017年 zhn. All rights reserved. // import UIKit class ZHNhomePageCoinCell: ZHNhomePageArchiveCell { var coinModel: ZHNhomePageCoinModel? { didSet { guard let coinCount = coinModel?.count else {return} guard let _ = coinModel?.item else {return} contentCollectionView.reloadData() count = coinCount } } // MARK - life cycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // 1. 标题上的数据设置 name = "最近投币" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ZHNhomePageCoinCell { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let count = coinModel?.count else {return 0} let fitCount = count > 2 ? 2 : count return fitCount } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: karchiveCollectionViewCellReuseKey, for: indexPath) as! ZHNhomePageArchiveCollectionViewCell cell.statusModel = coinModel?.item?[indexPath.row] return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let model = coinModel?.item?[indexPath.row] else {return} YSNotificationHelper.homePageSelectedNormalNotification(item: model) } }
mit
7ef9de0a83144c3134bef901c76f13d6
34.632653
167
0.689003
4.731707
false
false
false
false
hachinobu/CleanQiitaClient
CleanQiitaClient/RoutingImpl/ItemList/UserItemListRoutingImpl.swift
1
1414
// // UserItemListRoutingImpl.swift // CleanQiitaClient // // Created by Nishinobu.Takahiro on 2016/10/04. // Copyright © 2016年 hachinobu. All rights reserved. // import Foundation import DataLayer import DomainLayer import PresentationLayer public class UserItemListRoutingImpl: AllItemListRoutingImpl { override public func segueItem(id: String) { let stockersRepository = StockersRepositoryImpl.shared let stockRepository = StockItemRepositoryImpl.shared let itemRepository = ItemRepositoryImpl.shared let useCase = AllItemUseCaseImpl(stockItemRepository: stockRepository, stockersRepository: stockersRepository, itemRepository: itemRepository, itemId: id) //ItemPresenterImplFromUserItemを使うとタップした時にRoutingを呼ばないPresenter // let presenter = ItemPresenterImplFromUserItem(useCase: useCase) let presenter = ItemPresenterImplFromAllItem(useCase: useCase) let vc = UIStoryboard(name: "ItemScreen", bundle: Bundle(for: ItemViewController.self)).instantiateInitialViewController() as! ItemViewController let routing = UserItemRoutingImpl() routing.viewController = vc vc.injection(presenter: presenter, routing: routing) viewController?.navigationController?.pushViewController(vc, animated: true) } }
mit
0efc945952cf079e237326385c174074
36.27027
162
0.728064
4.855634
false
false
false
false
leznupar999/SSYoutubeParser
SSYoutubeParser/ViewController.swift
1
1796
// // ViewController.swift // SSYoutubeParser // // Created by leznupar999 on 2015/06/03. // Copyright (c) 2015 leznupar999. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var avPlayerView: AVPlayerView! override func viewDidLoad() { super.viewDidLoad() self.setupVideo() } func setupVideo() { SSYoutubeParser.h264videosWithYoutubeID("b2fjU9cmjXg") { (videoDictionary) -> Void in //let videoSmallURL = videoDictionary["small"] let videoMediumURL = videoDictionary["medium"] //let videoHD720URL = videoDictionary["hd720"] if let urlStr = videoMediumURL { if let playerItem:AVPlayerItem = AVPlayerItem(URL: NSURL(string: urlStr)!) { self.avPlayerView.player = AVPlayer(playerItem: playerItem) playerItem.addObserver(self, forKeyPath: "status", options: [.New,.Old,.Initial], context: nil) } } } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "status" { let change2 = change! let changeOld = change2["old"] as? NSNumber let changeNew = change2["new"] as? NSNumber let status = object!.status as AVPlayerItemStatus if changeOld == 0 && changeNew == 1 && status == AVPlayerItemStatus.ReadyToPlay { self.avPlayerView.player.play() } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } }
mit
78844a912066bde0dce3d05c864198a5
32.886792
157
0.601336
4.701571
false
false
false
false
gitdoapp/SoundCloudSwift
SoundCloudSwift/Source/Core/Entities/RequestConvertible.swift
2
1211
import Foundation import Alamofire /// Request creation struct struct RequestConvertible { // MARK: - Attributes private var path: String private var parameters: [String: AnyObject] private var method: Alamofire.Method // MARK: - Constructors /** Initializes a RequestConvertible object - Parameters: - path: The URL string representation of the base path - parameters: The dictionary representation of the query parameters - method: The HTTP request method _GET, POST, PUT, DELETE_ - Returns: An RequestConvertible object initialized with given parameters */ init(path: String, parameters: [String: AnyObject], method: Alamofire.Method = .GET) { self.path = path self.parameters = parameters self.method = method } // MARK: - Interface /// Generates the proper NSURLRequest from the current object func request() -> NSURLRequest { var request = NSMutableURLRequest(URL: NSURL(string: path)!) let enconding = ParameterEncoding.URLEncodedInURL (request, _) = enconding.encode(request, parameters: parameters) return request } }
mit
02e207468ce24230886cc1a528b489ca
29.3
90
0.658134
5.175214
false
false
false
false
stripe/stripe-ios
StripeCore/StripeCore/Source/Localization/STPLocalizationUtils.swift
1
3909
// // STPLocalizationUtils.swift // StripeCore // // Created by Brian Dorfman on 8/11/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) public final class STPLocalizationUtils { /// Acts like NSLocalizedString but tries to find the string in the Stripe /// bundle first if possible. /// /// If the main app has a localization that we do not support, we want to switch /// to pulling strings from the main bundle instead of our own bundle so that /// users can add translations for our strings without having to fork the sdk. /// At launch, NSBundles' store what language(s) the user requests that they /// actually have translations for in `preferredLocalizations`. /// We compare our framework's resource bundle to the main app's bundle, and /// if their language choice doesn't match up we switch to pulling strings /// from the main bundle instead. /// This also prevents language mismatches. E.g. the user lists portuguese and /// then spanish as their preferred languages. The main app supports both so all its /// strings are in pt, but we support spanish so our bundle marks es as our /// preferred language and our strings are in es. /// If the main bundle doesn't have the correct string, we'll always fall back to /// using the Stripe bundle so we don't inadvertently show an untranslated string. static func localizedStripeStringUseMainBundle( bundleLocator: BundleLocatorProtocol.Type ) -> Bool { if bundleLocator.resourcesBundle.preferredLocalizations.first != Bundle.main.preferredLocalizations.first { return true } return false } static let UnknownString = "STPStringNotFound" public class func localizedStripeString( forKey key: String, bundleLocator: BundleLocatorProtocol.Type ) -> String { if languageOverride != nil { return testing_localizedStripeString(forKey: key, bundleLocator: bundleLocator) } if localizedStripeStringUseMainBundle(bundleLocator: bundleLocator) { // Per https://developer.apple.com/documentation/foundation/bundle/1417694-localizedstring, // iOS will give us an empty string if a string isn't found for the specified key. // Work around this by specifying an unknown sentinel string as the value. If we get that value back, // we know that the string wasn't present in the bundle. let userTranslation = Bundle.main.localizedString( forKey: key, value: UnknownString, table: nil ) if userTranslation != UnknownString { return userTranslation } } return bundleLocator.resourcesBundle.localizedString( forKey: key, value: nil, table: nil ) } // MARK: - Testing static var languageOverride: String? static func overrideLanguage(to string: String?) { STPLocalizationUtils.languageOverride = string } static func testing_localizedStripeString( forKey key: String, bundleLocator: BundleLocatorProtocol.Type ) -> String { var bundle = bundleLocator.resourcesBundle if let languageOverride = languageOverride { let lprojPath = bundle.path(forResource: languageOverride, ofType: "lproj") if let lprojPath = lprojPath { bundle = Bundle(path: lprojPath)! } } return bundle.localizedString(forKey: key, value: nil, table: nil) } } /// Use to explicitly ignore static analyzer warning: /// "User-facing text should use localized string macro". @inline(__always) @_spi(STP) public func STPNonLocalizedString(_ string: String) -> String { return string }
mit
bfbfbd3b25faca7fb8ec064347727b6e
39.28866
113
0.661208
4.854658
false
false
false
false
Vostro162/VaporTelegram
Sources/App/ForwardMessage+Extensions.swift
1
941
// // ForwardMessage+Extensions.swift // VaporTelegram // // Created by Marius Hartig on 11.05.17. // // import Foundation import Vapor // MARK: - JSON extension ForwardMessage: JSONInitializable { public init(json: JSON) throws { guard let fromJSON = json["forward_from"], let from = try? User(json: fromJSON), let dateDouble = json["forward_date"]?.double else { throw VaporTelegramError.parsing } if let chatJSON = json["forward_from_chat"], let chat = try? Chat(json: chatJSON) { self.chat = chat } else { self.chat = nil } if let messageId = json["forward_from_message_id"]?.int { self.messageId = messageId } else { self.messageId = nil } self.from = from self.date = Date(timeIntervalSince1970: dateDouble) } }
mit
cb7c617654a37a7bcbf2d290a6081554
23.763158
91
0.550478
4.316514
false
false
false
false
OpenKitten/MongoKitten
Sources/MongoClient/Channel+Connection.swift
2
1488
import NIO import MongoCore internal struct MongoContextOption: ChannelOption { internal typealias Value = MongoClientContext } internal struct ClientConnectionParser: ByteToMessageDecoder { typealias InboundOut = MongoServerReply private let context: MongoClientContext private var parser: MongoServerReplyDeserializer internal init(context: MongoClientContext) { self.context = context self.parser = MongoServerReplyDeserializer(logger: context.logger) } mutating func decode(context ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { do { let result = try parser.parse(from: &buffer) if let reply = parser.takeReply(), !context.handleReply(reply) { print("Reply received from MongoDB, but no request was waiting for the result.") } return result } catch { self.context.cancelQueries(error) self.context.didError = true throw error } } mutating func decodeLast(context ctx: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { return try decode(context: ctx, buffer: &buffer) } // TODO: this does not belong here but on the next handler func errorCaught(context ctx: ChannelHandlerContext, error: Error) { // So that it can take the remaining queries and re-try them ctx.close(promise: nil) } }
mit
9f34e3158d2ab84807768b8e1932b7cb
32.818182
131
0.678763
4.862745
false
false
false
false
ello/ello-ios
Specs/Controllers/Stream/Cells/PromotionalHeaderCellSpec.swift
1
10721
//// /// PromotionalHeaderCellSpec.swift // @testable import Ello import Quick import Nimble import PINRemoteImage import PINCache class PromotionalHeaderCellSpec: QuickSpec { enum Style { case narrow case wide case iPad var width: CGFloat { switch self { case .narrow: return 320 case .wide: return 375 case .iPad: return 768 } } func frame(_ height: CGFloat) -> CGRect { return CGRect(x: 0, y: 0, width: self.width, height: height) } } override func spec() { describe("PromotionalHeaderCell") { var subject: PromotionalHeaderCell! func setImages() { subject.specs().postedByAvatar.setImage( specImage(named: "specs-avatar"), for: .normal ) subject.setImage(specImage(named: "specs-category-image.jpg")!) } describe("snapshots") { let shortBody = "Aliquam erat volutpat. Vestibulum ante." let longBody = "Nullam scelerisque pulvinar enim. Aliquam erat volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis eleifend lobortis sapien vitae ultrices. Interdum et malesuada fames ac ante ipsum primis in faucibus. Mauris interdum accumsan laoreet. Mauris sed massa est." let shortCtaCaption = "tap for more" let longCtaCaption = "tap for more and then you should do something else" let expectations: [( String, kind: PageHeader.Kind, name: String, isSponsored: Bool, body: String, ctaCaption: String, style: Style )] = [ ( "category not sponsored, narrow", kind: .category, name: "A Longer Title Goes Here, does it wrap?", isSponsored: false, body: shortBody, ctaCaption: shortCtaCaption, style: .narrow ), ( "category not sponsored, wide", kind: .category, name: "Art", isSponsored: false, body: shortBody, ctaCaption: shortCtaCaption, style: .wide ), ( "category not sponsored, iPad", kind: .category, name: "Art", isSponsored: false, body: shortBody, ctaCaption: shortCtaCaption, style: .iPad ), ( "category sponsored, narrow", kind: .category, name: "Art", isSponsored: true, body: shortBody, ctaCaption: shortCtaCaption, style: .narrow ), ( "category sponsored, wide", kind: .category, name: "Art", isSponsored: true, body: shortBody, ctaCaption: shortCtaCaption, style: .wide ), ( "category sponsored, iPad", kind: .category, name: "Art", isSponsored: true, body: shortBody, ctaCaption: shortCtaCaption, style: .iPad ), ( "category long body, narrow", kind: .category, name: "Art", isSponsored: true, body: longBody, ctaCaption: shortCtaCaption, style: .narrow ), ( "category long body, wide", kind: .category, name: "Art", isSponsored: true, body: longBody, ctaCaption: shortCtaCaption, style: .wide ), ( "category long body, iPad", kind: .category, name: "Art", isSponsored: true, body: longBody, ctaCaption: shortCtaCaption, style: .iPad ), ( "category long body, long cta caption, narrow", kind: .category, name: "Art", isSponsored: true, body: longBody, ctaCaption: longCtaCaption, style: .narrow ), ( "category long body, long cta caption, wide", kind: .category, name: "Art", isSponsored: true, body: longBody, ctaCaption: longCtaCaption, style: .wide ), ( "category long body, long cta caption, iPad", kind: .category, name: "Art", isSponsored: true, body: longBody, ctaCaption: longCtaCaption, style: .iPad ), ( "generic not sponsored, narrow", kind: .generic, name: "A Longer Title Goes Here, does it wrap?", isSponsored: false, body: shortBody, ctaCaption: shortCtaCaption, style: .narrow ), ( "generic not sponsored, wide", kind: .generic, name: "Art", isSponsored: false, body: shortBody, ctaCaption: shortCtaCaption, style: .wide ), ( "generic not sponsored, iPad", kind: .generic, name: "Art", isSponsored: false, body: shortBody, ctaCaption: shortCtaCaption, style: .iPad ), ( "generic sponsored, narrow", kind: .generic, name: "Art", isSponsored: true, body: shortBody, ctaCaption: shortCtaCaption, style: .narrow ), ( "generic sponsored, wide", kind: .generic, name: "Art", isSponsored: true, body: shortBody, ctaCaption: shortCtaCaption, style: .wide ), ( "generic sponsored, iPad", kind: .generic, name: "Art", isSponsored: true, body: shortBody, ctaCaption: shortCtaCaption, style: .iPad ), ( "generic long body, narrow", kind: .generic, name: "Art", isSponsored: false, body: longBody, ctaCaption: shortCtaCaption, style: .narrow ), ( "generic long body, wide", kind: .generic, name: "Art", isSponsored: false, body: longBody, ctaCaption: shortCtaCaption, style: .wide ), ( "generic long body, iPad", kind: .generic, name: "Art", isSponsored: false, body: longBody, ctaCaption: shortCtaCaption, style: .iPad ), ( "generic long body, long cta caption, narrow", kind: .generic, name: "Art", isSponsored: false, body: longBody, ctaCaption: longCtaCaption, style: .narrow ), ( "generic long body, long cta caption, wide", kind: .generic, name: "Art", isSponsored: false, body: longBody, ctaCaption: longCtaCaption, style: .wide ), ( "generic long body, long cta caption, iPad", kind: .generic, name: "Art", isSponsored: false, body: longBody, ctaCaption: longCtaCaption, style: .iPad ) ] for (desc, kind, name, isSponsored, body, ctaCaption, style) in expectations { it("has valid screenshot for \(desc)") { let user: User = User.stub(["username": "bob"]) let xhdpi = Attachment.stub([ "url": "http://ello.co/avatar.png", "height": 0, "width": 0, "type": "png", "size": 0 ] ) let image = Asset.stub(["xhdpi": xhdpi]) let pageHeader = PageHeader.stub([ "header": name, "user": user, "subheader": body, "ctaCaption": ctaCaption, "ctaURL": "http://google.com", "image": image, "kind": kind, ]) pageHeader.isSponsored = isSponsored let height = PromotionalHeaderCellSizeCalculator.calculatePageHeaderHeight( pageHeader, htmlHeight: nil, cellWidth: style.width ) subject = PromotionalHeaderCell(frame: style.frame(height)) let item = StreamCellItem(jsonable: pageHeader, type: .promotionalHeader) PromotionalHeaderCellPresenter.configure( subject, streamCellItem: item, streamKind: .category(.category("Design"), .featured), indexPath: IndexPath(item: 0, section: 0), currentUser: nil ) setImages() expectValidSnapshot(subject) } } } } } }
mit
f715208d1e4f888f837316e9dfe04952
46.438053
330
0.411156
5.720918
false
false
false
false
CatchChat/Yep
OpenGraphTests/OpenGraphTests.swift
1
1724
// // OpenGraphTests.swift // OpenGraphTests // // Created by NIX on 16/5/20. // Copyright © 2016年 Catch Inc. All rights reserved. // import XCTest @testable import OpenGraph final class OpenGraphTests: XCTestCase { func testBaiduOpenGraph() { let baiduURL = NSURL(string: "http://www.baidu.com")! let expectation = expectationWithDescription("baidu open graph") openGraphWithURL(baiduURL, failureHandler: nil) { openGraph in print("baidu openGraph: \(openGraph)") expectation.fulfill() } waitForExpectationsWithTimeout(5, handler: nil) } func testItunesOpenGraph() { // 单曲 let iTunesURL = NSURL(string: "https://itunes.apple.com/cn/album/hello-single/id1051365605?i=1051366040&l=en")! let queryItem = NSURLQueryItem(name: "at", value: "1010l9k7") let expectation = expectationWithDescription("iTunes open graph") openGraphWithURL(iTunesURL, failureHandler: nil) { openGraph in print("iTunes openGraph: \(openGraph)") if openGraph.URL.opengraphtests_containsQueryItem(queryItem) { expectation.fulfill() } } waitForExpectationsWithTimeout(10, handler: nil) } func testGetTitleOfURL() { let URL = NSURL(string: "https://www.apple.com")! let expectation = expectationWithDescription("get title of URL: \(URL)") titleOfURL(URL, failureHandler: nil, completion: { title in print("title: \(title)") if !title.isEmpty { expectation.fulfill() } }) waitForExpectationsWithTimeout(10, handler: nil) } }
mit
a4d77c9d805557fd7cb35ba5a648cecc
24.25
119
0.620268
4.566489
false
true
false
false
elkanaoptimove/OptimoveSDK
OptimoveSDK/Common/Singletons/UserInSession.swift
1
9930
// // UserInSession.swift // OptimoveSDKDev // // Created by Mobile Developer Optimove on 11/09/2017. // Copyright © 2017 Optimove. All rights reserved. // import Foundation class UserInSession: Synchronizable { let lock:NSLock enum UserDefaultsKeys: String { case configurationEndPoint = "configurationEndPoint" case isMbaasOptIn = "isMbaasOptIn" case isOptiTrackOptIn = "isOptiTrackOptIn" case isFirstConversion = "isFirstConversion" case tenantToken = "tenantToken" case siteID = "siteID" case version = "version" case customerID = "customerID" case visitorID = "visitorID" case deviceToken = "deviceToken" case fcmToken = "fcmToken" case defaultFcmToken = "defaultFcmToken" case isFirstLaunch = "isFirstLaunch" case userAgentHeader = "userAgentHeader" case unregistrationSuccess = "unregistrationSuccess" case registrationSuccess = "registrationSuccess" case optSuccess = "optSuccess" case isSetUserIdSucceed = "isSetUserIdSucceed" case isClientHasFirebase = "userHasFirebase" case isClientUseFirebaseMessaging = "isClientUseFirebaseMessaging" case apnsToken = "apnsToken" case hasConfigurationFile = "hasConfigurationFile" case topics = "topic" case openAppTime = "openAppTime" case clientUseBackgroundExecution = "clientUseBackgroundExecution" case lastPingTime = "lastPingTime" case realtimeSetUserIdFailed = "realtimeSetUserIdFailed" } static let shared = UserInSession() private init() { lock = NSLock() } //MARK: Persist data var customerID:String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.customerID.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.customerID.rawValue) } } var visitorID:String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.visitorID.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.visitorID.rawValue) } } var apnsToken: Data? { get { return UserDefaults.standard.data(forKey: UserDefaultsKeys.apnsToken.rawValue) } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.apnsToken.rawValue) } } //MARK: Initializtion Flags var configurationEndPoint: String { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.configurationEndPoint.rawValue) { return id } return "" } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.configurationEndPoint.rawValue) } } var siteID:Int? { get { if let id = UserDefaults.standard.value(forKey: UserDefaultsKeys.siteID.rawValue) as? Int { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.siteID.rawValue) } } var tenantToken: String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.tenantToken.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.tenantToken.rawValue) } } var version:String? { get { if let id = UserDefaults.standard.string(forKey: UserDefaultsKeys.version.rawValue) { return id } return nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.version.rawValue) } } var hasConfigurationFile : Bool? { get { return UserDefaults.standard.value(forKey: UserDefaultsKeys.hasConfigurationFile.rawValue) as? Bool } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.hasConfigurationFile.rawValue) } } var isClientHasFirebase : Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.isClientHasFirebase.rawValue)} set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isClientHasFirebase.rawValue) } } var isClientUseFirebaseMessaging : Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.isClientUseFirebaseMessaging.rawValue)} set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isClientUseFirebaseMessaging.rawValue) } } // MARK: Optipush Flags var isMbaasOptIn: Bool? { get { lock.lock() let val = UserDefaults.standard.value(forKey: UserDefaultsKeys.isMbaasOptIn.rawValue) as? Bool lock.unlock() return val } set { lock.lock() self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isMbaasOptIn.rawValue) lock.unlock() } } var isUnregistrationSuccess : Bool { get { return (UserDefaults.standard.value(forKey: UserDefaultsKeys.unregistrationSuccess.rawValue) as? Bool) ?? true } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.unregistrationSuccess.rawValue) } } var isRegistrationSuccess : Bool { get { return (UserDefaults.standard.value(forKey: UserDefaultsKeys.registrationSuccess.rawValue) as? Bool) ?? true } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.registrationSuccess.rawValue) } } var isOptRequestSuccess : Bool { get { return (UserDefaults.standard.value(forKey: UserDefaultsKeys.optSuccess.rawValue) as? Bool) ?? true } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.optSuccess.rawValue) } } var isFirstConversion : Bool? { get { return UserDefaults.standard.value(forKey: UserDefaultsKeys.isFirstConversion.rawValue) as? Bool } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isFirstConversion.rawValue) } } var defaultFcmToken: String? { get { return UserDefaults.standard.string(forKey: UserDefaultsKeys.defaultFcmToken.rawValue) ?? nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.defaultFcmToken.rawValue) } } var fcmToken: String? { get { return UserDefaults.standard.string(forKey: UserDefaultsKeys.fcmToken.rawValue) ?? nil } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.fcmToken.rawValue) } } // MARK: OptiTrack Flags var isOptiTrackOptIn: Bool? { get { lock.lock() let val = UserDefaults.standard.value(forKey: UserDefaultsKeys.isOptiTrackOptIn.rawValue) as? Bool lock.unlock() return val } set { lock.lock() self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.isOptiTrackOptIn.rawValue) lock.unlock() } } var lastPingTime: TimeInterval { get { return UserDefaults.standard.double(forKey: UserDefaultsKeys.lastPingTime.rawValue)} set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.lastPingTime.rawValue) } } var isSetUserIdSucceed : Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.isSetUserIdSucceed.rawValue)} set { self.setDefaultObject(forObject: newValue as Bool, key: UserDefaultsKeys.isSetUserIdSucceed.rawValue) } } // MARK: Real time flags var realtimeSetUserIdFailed: Bool { get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.realtimeSetUserIdFailed.rawValue) } set { self.setDefaultObject(forObject: newValue as Any, key: UserDefaultsKeys.realtimeSetUserIdFailed.rawValue) } } }
mit
0bdd0ca86849f735a73a074ed3cdac73
31.554098
122
0.550307
5.234054
false
false
false
false
luispadron/UICircularProgressRing
Example/UICircularProgressRingExample/Examples/ProgressRingCustomizationExample.swift
1
5001
// // ProgressRingCustomizationExample.swift // UICircularProgressRingExample // // Created by Luis on 5/30/20. // Copyright © 2020 Luis. All rights reserved. // import SwiftUI import UICircularProgressRing struct ProgressRingCustomizationExample: View { let customizationViews = CustomizationView.allCases var body: some View { return List(customizationViews) { view in ModifierRow(customizationView: view) } .navigationBarTitle("Customization") } } // MARK: Modifier Views enum CustomizationView: String, CaseIterable { case lineWidth case color case axis case clockwise } extension CustomizationView: Identifiable { var id: String { rawValue } } struct ModifierRow: View { let customizationView: CustomizationView var body: some View { VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading) { Text(customizationView.title) .font(.system(.headline)) .bold() Text(customizationView.description) .font(.system(.subheadline)) .foregroundColor(.gray) } customizationView.view } .padding(.vertical, 16) } } struct LineWidthModifier: View { @State var lineWidth: Double = 20 var body: some View { VStack { Slider(value: $lineWidth, in: 5...40) { Text("Line width:") } ProgressRing( progress: .constant(.percent(0.7)), innerRingStyle: .init(color: .color(.blue), strokeStyle: .init(lineWidth: CGFloat(lineWidth))) ) .frame(width: 200, height: 200) } } } struct ColorModifier: View { @State var isGradient = false var body: some View { VStack { Toggle(isOn: $isGradient) { Text(".gradient() vs. .color()") } ProgressRing( progress: .constant(.percent(0.7)), innerRingStyle: .init(color: color, strokeStyle: .init(lineWidth: 16)) ) .animation(.easeInOut(duration: 1)) .frame(width: 200, height: 200) } } var color: RingColor { if isGradient { return RingColor.gradient(.init(gradient: .init(colors: [.red, .green, .blue]), center: .top)) } else { return RingColor.color(.blue) } } } struct AxisModifier: View { let axes: [RingAxis] = [.top, .bottom, .leading, .trailing] @State private var selectedAxis = 0 var body: some View { VStack { Picker("", selection: $selectedAxis) { ForEach(Array(axes.enumerated()), id: \.element) { index, axis in Text(axis.title).tag(index) } } .pickerStyle(SegmentedPickerStyle()) ProgressRing( progress: .constant(.percent(0.7)), axis: axes[selectedAxis] ) .animation(.easeInOut(duration: 1)) .frame(width: 200, height: 200) } } } struct ClockwiseModifier: View { @State private var clockwise = false var body: some View { VStack { Toggle(isOn: $clockwise) { Text("Clockwise") } ProgressRing( progress: .constant(.percent(0.7)), clockwise: clockwise ) .animation(.easeInOut(duration: 1)) .frame(width: 200, height: 200) } } } // MARK: - Extensions private extension CustomizationView { var title: String { switch self { case .lineWidth: return ".lineWidth" case .color: return ".color" case .axis: return ".axis" case .clockwise: return ".clockwise" } } var description: String { switch self { case .lineWidth: return "Modifies the width of the inner or outer ring." case .color: return "Either .color or .gradient." case .axis: return "Which axis to begin drawing." case .clockwise: return "Draw in a clockwise manner or not." } } var view: AnyView { switch self { case .lineWidth: return AnyView(LineWidthModifier()) case .color: return AnyView(ColorModifier()) case .axis: return AnyView(AxisModifier()) case .clockwise: return AnyView(ClockwiseModifier()) } } } private extension RingAxis { var title: String { switch self { case .top: return ".top" case .bottom: return ".bottom" case .leading: return ".leading" case .trailing: return ".trailing" } } }
mit
427f9febb1700e9192b4c3c655a83bf5
23.630542
110
0.5298
4.677268
false
false
false
false
czgarrett/nametag
NameTag/NameTag/NameTag.playground/Contents.swift
1
3348
//: Playground - noun: a place where people can play import UIKit let dpi: CGFloat = 600.0 // dots per inch for the image. CGFloat is the floating point type used in core graphics let imageSizeInches = CGSizeMake(3.375, 2.3333) // Avery 5395 labels let imageSizePixels = CGSizeMake(imageSizeInches.width * dpi, imageSizeInches.height*dpi) let imageRect = CGRect(origin: CGPoint.zero, size: imageSizePixels) UIGraphicsBeginImageContext(imageSizePixels) // This sets up a context into which we can draw images // Get the context let context = UIGraphicsGetCurrentContext() // Draw our beautiful name tag // Fill it with white so the preview looks good. Or pick a light color that won't use lots of printer ink. ☺️ CGContextSetFillColorWithColor(context, UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0).CGColor) CGContextFillRect(context, imageRect) // Draw a border around the edge // the border is inset by 60px let borderRect = CGRectInset(imageRect, 60.0, 60.0) // Set a color for the border CGContextSetStrokeColorWithColor(context, UIColor.purpleColor().CGColor) // Create a bezier path for the border let bezierPath = UIBezierPath(roundedRect: borderRect, cornerRadius: 75.0) bezierPath.lineWidth = 18.0 bezierPath.stroke() // Draw our name // For a list of font names, go to iosfonts.com let font = UIFont(name: "Georgia-Bold", size: 240.0)! // it's a big size because our image is actually pretty big in pixels let name = "Chris Garrett" as NSString // Create a paragraph style for our name let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .Center // Create a dictionary of text attributes let textAttributes = [ NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: paragraphStyle ] var nameRect = borderRect nameRect.size.height = 240.0 nameRect.origin.y = 120.0 name.drawInRect(nameRect, withAttributes: textAttributes) let info = "I ❤️ 🐶🐱⛷🚴 and ⛵️" as NSString var infoRect = nameRect infoRect.origin.y = 600.0 let infoAttributes = [ NSFontAttributeName: UIFont.systemFontOfSize(120.0), NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: paragraphStyle ] info.drawInRect(infoRect, withAttributes: infoAttributes) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // clean up after ourselves let folderName = "NameTag" // Playgrounds get their own sandboxed folder for documents. Here we're going to get that folder so that we can save our image let documentDirectoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! let folder = documentDirectoryURL.URLByAppendingPathComponent(folderName) // You can ctrl-click on this URL to the right, and choose Open URL to navigate to it -> let fileMgr = NSFileManager.defaultManager() if (!fileMgr.fileExistsAtPath(folder.path!)) { do { try fileMgr.createDirectoryAtURL(folder, withIntermediateDirectories: false, attributes: nil) } catch _ { } } let filePath = folder.URLByAppendingPathComponent("NameTag.png") // Convert the in-memory image into file data let fileData = UIImagePNGRepresentation(image) // Save the data fileData?.writeToFile(filePath.path!, atomically: true)
mit
12c7da124f48252856c25698e7142695
32.25
162
0.769925
4.279279
false
false
false
false
darina/omim
iphone/Maps/UI/PlacePage/Components/ElevationProfile/ElevationProfileDescriptionCell.swift
5
520
class ElevationProfileDescriptionCell: UICollectionViewCell { @IBOutlet private var titleLabel: UILabel! @IBOutlet private var valueLabel: UILabel! @IBOutlet var imageView: UIImageView! func configure(title: String, value: String, imageName: String) { titleLabel.text = title valueLabel.text = value imageView.image = UIImage(named: imageName) } override func prepareForReuse() { super.prepareForReuse() titleLabel.text = "" valueLabel.text = "" imageView.image = nil } }
apache-2.0
17b7dc841b14f48016a94e576abb3e4e
27.888889
67
0.715385
4.770642
false
true
false
false
ChristianKienle/highway
Sources/XCBuild/Export/ExportOptions.swift
1
6684
import Foundation /// Credits for documentation: man xcodebuild public struct ExportOptions: Codable { public init() {} // Key: compileBitcode // For non-App Store exports, should Xcode re-compile the app from bitcode? // True if not set. public var compileBitcode: Bool? // Key: embedOnDemandResourcesAssetPacksInBundle // For non-App Store exports, if the app uses On Demand Resources and this is YES, asset packs are embedded in the app bundle so that the app can be tested without a server to host asset packs. Defaults to YES unless onDemandResourcesAssetPacksBaseURL is specified. public var embedOnDemandResourcesAssetPacksInBundle: Bool? // If the app is using CloudKit, this configures the "com.apple.developer.icloud-container-environment" entitlement. Available options vary depending on the type of provisioning profile used, but may include: Development and Production. public var iCloudContainerEnvironment: String? // For manual signing only. Provide a certificate name, SHA-1 hash, or automatic selector to use for signing. Automatic selectors allow Xcode to pick the newest installed certificate of a particular type. The available automatic selectors are "Mac Installer Distribution" and "Developer ID Installer". Defaults to an automatic certificate selector matching the current distribution method. public var installerSigningCertificate: String? // For non-App Store exports, users can download your app over the web by opening your distribution manifest file in a web browser. To generate a distribution manifest, the value of this key should be a dictionary with three sub-keys: appURL, displayImageURL, fullSizeImageURL. The additional sub-key assetPackManifestURL is required when using on-demand resources. public var manifest: [String: String]? public enum Method: String, Codable { case appStore = "app-store" case package = "package" case adhoc = "ad-hoc" case enterprise = "enterprise" case development = "development" case developerId = "developer-id" case macApplication = "mac-application" } // Describes how Xcode should export the archive. Available options: app-store, package, ad-hoc, enterprise, development, developer-id, and mac-application. The list of options varies based on the type of archive. Defaults to development. public var method: Method = .development // For non-App Store exports, if the app uses On Demand Resources and embedOnDemandResourcesAssetPacksInBundle isn't YES, this should be a base URL specifying where asset packs are going to be hosted. This configures the app to download asset packs from the specified URL. public var onDemandResourcesAssetPacksBaseURL: String? // For manual signing only. Specify the provisioning profile to use for each executable in your app. Keys in this dictionary are the bundle identifiers of executables; values are the provisioning profile name or UUID to use. public struct ProvisioningProfiles: Codable { public init() { } public enum Profile { public typealias UUIDString = String case named(String) case identifiedBy(UUIDString) var value: String { switch self { case .named(let name): return name case .identifiedBy(let uuid): return uuid } } } public mutating func addProfile(_ profile: Profile, forBundleIdentifier bundleIdentifier: String) { _profiles[bundleIdentifier] = profile.value } private var _profiles = [String:String]() public init(from decoder: Decoder) throws { _profiles = try Dictionary<String, String>(from: decoder) } public func encode(to encoder: Encoder) throws { try _profiles.encode(to: encoder) } } public var provisioningProfiles: ProvisioningProfiles? // For manual signing only. Provide a certificate name, SHA-1 hash, or automatic selector to use for signing. Automatic selectors allow Xcode to pick the newest installed certificate of a particular type. The available automatic selectors are "Mac App Distribution", "iOS Distribution", "iOS Developer", "Developer ID Application", and "Mac Developer". Defaults to an automatic certificate selector matching the current distribution method. public var signingCertificate: String? // The signing style to use when re-signing the app for distribution. Options are manual or automatic. Apps that were automatically signed when archived can be signed manually or automatically during distribution, and default to automatic. Apps that were manually signed when archived must be manually signed during distribtion, so the value of signingStyle is ignored. public enum SigningStyle: String, Codable { case manual, automatic } public var signingStyle: SigningStyle? // Should symbols be stripped from Swift libraries in your IPA? Defaults to YES. public var stripSwiftSymbols: Bool? // The Developer Portal team to use for this export. Defaults to the team used to build the archive. public var teamID : String? //For non-App Store exports, should Xcode thin the package for one or more device variants? Available options: <none> (Xcode produces a non-thinned universal app), <thin-for-all-variants> (Xcode produces a universal app and all available thinned variants), or a model identifier for a specific device (e.g. "iPhone7,1"). Defaults to <none>. public enum Thinning: RawRepresentable, Codable { case none case all case device(modelIdentifier: String) public init?(rawValue: String) { switch rawValue { case "<none>": self = .none case "<thin-for-all-variants>": self = .all default: self = .device(modelIdentifier: rawValue) } } public var rawValue: String { switch self { case .none: return "<none>" case .all: return "<thin-for-all-variants>" case .device(let modelIdentifier): return modelIdentifier } } } public var thinning: Thinning? // For App Store exports, should the package include bitcode? Defaults to YES. public var uploadBitcode: Bool? // For App Store exports, should the package include symbols? Defaults to YES. public var uploadSymbols: Bool? }
mit
e371ae8016de7ad87bd7c93ba01bf1fa
56.128205
444
0.694794
5.121839
false
false
false
false
codestergit/swift
test/ClangImporter/enum-error.swift
2
4327
// REQUIRES: OS=macosx // RUN: %target-swift-frontend -DVALUE -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=VALUE // RUN: %target-swift-frontend -DEMPTYCATCH -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=EMPTYCATCH // RUN: %target-swift-frontend -DASQEXPR -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=ASQEXPR // RUN: %target-swift-frontend -DASBANGEXPR -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=ASBANGEXPR // RUN: %target-swift-frontend -DCATCHIS -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=CATCHIS // RUN: %target-swift-frontend -DCATCHAS -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=CATCHAS // RUN: %target-swift-frontend -DGENERICONLY -emit-sil %s -import-objc-header %S/Inputs/enum-error.h | %FileCheck %s -check-prefix=GENERICONLY // RUN: %target-swift-frontend -emit-sil %s -import-objc-header %S/Inputs/enum-error.h -verify // RUN: echo '#include "enum-error.h"' > %t.m // RUN: %target-swift-ide-test -source-filename %s -print-header -header-to-print %S/Inputs/enum-error.h -import-objc-header %S/Inputs/enum-error.h -print-regular-comments --cc-args %target-cc-options -fsyntax-only %t.m -I %S/Inputs > %t.txt // RUN: %FileCheck -check-prefix=HEADER %s < %t.txt import Foundation func testDropCode(other: OtherError) -> OtherError.Code { return other.code } func testError() { let testErrorNSError = NSError(domain: TestErrorDomain, code: Int(TestError.TENone.rawValue), userInfo: nil) // Below are a number of test cases to make sure that various pattern and cast // expression forms are sufficient in pulling in the _NSBridgedError // conformance. #if VALUE // VALUE: TestError: _BridgedStoredNSError let terr = getErr(); terr #elseif EMPTYCATCH // EMPTYCATCH: TestError: _BridgedStoredNSError do { throw TestError(.TENone) } catch {} #elseif ASQEXPR // ASQEXPR: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC let wasTestError = testErrorNSError as? TestError; wasTestError #elseif ASBANGEXPR // ASBANGEXPR: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC let terr2 = testErrorNSError as! TestError; terr2 #elseif ISEXPR // ISEXPR: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC if (testErrorNSError is TestError) { print("true") } else { print("false") } #elseif CATCHIS // CATCHIS: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC do { throw TestError(.TETwo) } catch is TestError { } catch {} #elseif CATCHAS // CATCHAS: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC do { throw TestError(.TETwo) } catch let err as TestError { err } catch {} #elseif GENERICONLY // GENERICONLY: TestError: _BridgedStoredNSError func dyncast<T, U>(_ x: T) -> U { return x as! U } let _ : TestError = dyncast(testErrorNSError) #else // CHECK: sil_witness_table shared [serialized] TestError: _BridgedStoredNSError module __ObjC let terr = getErr() switch (terr) { case .TENone, .TEOne, .TETwo: break } // ok switch (terr) { case .TENone, .TEOne: break } // expected-error@-1 {{switch must be exhaustive, consider adding missing cases}} let _ = TestError.Code(rawValue: 2)! do { throw TestError(.TEOne) } catch is TestError { } catch {} #endif } // HEADER: struct TestError : _BridgedStoredNSError { // HEADER: let _nsError: NSError // HEADER: init(_nsError: NSError) // HEADER: static var _nsErrorDomain: String { get } // HEADER: enum Code : Int32, _ErrorCodeProtocol { // HEADER: init?(rawValue: Int32) // HEADER: var rawValue: Int32 { get } // HEADER: typealias _ErrorType = TestError // HEADER: case TENone // HEADER: case TEOne // HEADER: case TETwo // HEADER: } // HEADER: static var TENone: TestError.Code { get } // HEADER: static var TEOne: TestError.Code { get } // HEADER: static var TETwo: TestError.Code { get } // HEADER: } // HEADER: func getErr() -> TestError.Code
apache-2.0
19214f49f19ace76ccf266b3fcfa233a
36.95614
241
0.69725
3.359472
false
true
false
false
steelwheels/Coconut
CoconutData/Source/Data/CNEscapeCode.swift
1
24132
/** * @file CNEscapeCode.swift * @brief Define CNEscapeCode type * @par Copyright * Copyright (C) 2019 Steel Wheels Project */ import Foundation /* Reference: * - https://en.wikipedia.org/wiki/ANSI_escape_code * - https://qiita.com/PruneMazui/items/8a023347772620025ad6 * - http://www.termsys.demon.co.uk/vtansi.htm */ public enum CNEscapeCode { case string(String) case eot /* End of transmission (CTRL-D) */ case newline case tab case backspace /* = moveLeft(1) */ case delete /* Delete left 1 character */ case cursorUp(Int) case cursorDown(Int) case cursorForward(Int) case cursorBackward(Int) case cursorNextLine(Int) /* Moves cursor to beginning of the line n */ case cursorPreviousLine(Int) /* Moves cursor to beginning of the line n */ case cursorHolizontalAbsolute(Int) /* (Column) started from 1 */ case saveCursorPosition /* Save current cursor position */ case restoreCursorPosition /* Update cursor position by saved one */ case cursorPosition(Int, Int) /* (Row, Column) started from 1 */ case eraceFromCursorToEnd /* Clear from cursor to end of buffer */ case eraceFromCursorToBegin /* Clear from begining of buffer to cursor */ case eraceEntireBuffer /* Clear entire buffer */ case eraceFromCursorToRight /* Clear from cursor to end of line */ case eraceFromCursorToLeft /* Clear from cursor to beginning of line */ case eraceEntireLine /* Clear entire line */ case scrollUp(Int) /* Scroll up n lines */ case scrollDown(Int) /* Scroll down n lines */ case resetAll /* Clear text, reset cursor postion and tabstop */ case resetCharacterAttribute /* Reset all arributes for character */ case boldCharacter(Bool) /* Set/reset bold font */ case underlineCharacter(Bool) /* Set/reset underline font */ case blinkCharacter(Bool) /* Set/reset blink font */ case reverseCharacter(Bool) /* Set/reset reverse character */ case foregroundColor(CNColor) /* Set foreground color */ case defaultForegroundColor /* Set default foreground color */ case backgroundColor(CNColor) /* Set background color */ case defaultBackgroundColor /* Reset default background color */ case requestScreenSize /* Send request to receive screen size * Ps = 18 -> Report the size of the text area in characters as CSI 8 ; height ; width t */ case screenSize(Int, Int) /* Set screen size (Width, Height) */ case selectAltScreen(Bool) /* Do switch alternative screen (Yes/No) */ public func description() -> String { var result: String switch self { case .string(let str): result = "string(\"\(str)\")" case .eot: result = "endOfTrans" case .newline: result = "newline" case .tab: result = "tab" case .backspace: result = "backspace" case .delete: result = "delete" case .cursorUp(let n): result = "cursorUp(\(n))" case .cursorDown(let n): result = "cursorDown(\(n))" case .cursorForward(let n): result = "cursorForward(\(n))" case .cursorBackward(let n): result = "cursorBack(\(n))" case .cursorNextLine(let n): result = "cursorNextLine(\(n))" case .cursorPreviousLine(let n): result = "cursorPreviousLine(\(n))" case .cursorHolizontalAbsolute(let pos): result = "cursorHolizontalAbsolute(\(pos))" case .saveCursorPosition: result = "saveCursorPosition" case .restoreCursorPosition: result = "restoreCursorPosition" case .cursorPosition(let row, let col): result = "cursorPoisition(\(row),\(col))" case .eraceFromCursorToEnd: result = "eraceFromCursorToEnd" case .eraceFromCursorToBegin: result = "eraceFromCursorToBegin" case .eraceEntireBuffer: result = "eraceEntireBuffer" case .eraceFromCursorToRight: result = "eraceFromCursorToRight" case .eraceFromCursorToLeft: result = "eraceFromCursorToLeft" case .eraceEntireLine: result = "eraceEntireLine" case .scrollUp(let lines): result = "scrollUp(\(lines))" case .scrollDown(let lines): result = "scrollDown(\(lines))" case .resetAll: result = "resetAll" case .resetCharacterAttribute: result = "resetCharacterAttribute" case .boldCharacter(let flag): result = "boldCharacter(\(flag))" case .underlineCharacter(let flag): result = "underlineCharacter(\(flag))" case .blinkCharacter(let flag): result = "blinkCharacter(\(flag))" case .reverseCharacter(let flag): result = "reverseCharacter(\(flag))" case .foregroundColor(let col): result = "foregroundColor(\(col.rgbName))" case .defaultForegroundColor: result = "defaultForegroundColor" case .backgroundColor(let col): result = "backgroundColor(\(col.rgbName))" case .defaultBackgroundColor: result = "defaultBackgroundColor" case .requestScreenSize: result = "requestScreenSize" case .screenSize(let width, let height): result = "screenSize(\(width), \(height))" case .selectAltScreen(let selalt): result = "selectAltScreen(\(selalt))" } return result } public func encode() -> String { let ESC = Character.ESC var result: String switch self { case .string(let str): result = str case .eot: result = String(Character.EOT) case .newline: result = String(Character.CR) case .tab: result = String(Character.TAB) case .backspace: result = String(Character.BS) case .delete: result = String(Character.DEL) case .cursorUp(let n): result = "\(ESC)[\(n)A" case .cursorDown(let n): result = "\(ESC)[\(n)B" case .cursorForward(let n): result = "\(ESC)[\(n)C" case .cursorBackward(let n): result = "\(ESC)[\(n)D" case .cursorNextLine(let n): result = "\(ESC)[\(n)E" case .cursorPreviousLine(let n): result = "\(ESC)[\(n)F" case .cursorHolizontalAbsolute(let n): result = "\(ESC)[\(n)G" case .saveCursorPosition: result = "\(ESC)7" case .restoreCursorPosition: result = "\(ESC)8" case .cursorPosition(let row, let col): result = "\(ESC)[\(row);\(col)H" case .eraceFromCursorToEnd: result = "\(ESC)[0J" case .eraceFromCursorToBegin: result = "\(ESC)[1J" case .eraceEntireBuffer: result = "\(ESC)[2J" case .eraceFromCursorToRight: result = "\(ESC)[0K" case .eraceFromCursorToLeft: result = "\(ESC)[1K" case .eraceEntireLine: result = "\(ESC)[2K" case .scrollUp(let lines): result = "\(ESC)[\(lines)S" case .scrollDown(let lines): result = "\(ESC)[\(lines)T" case .resetAll: result = "\(ESC)c" case .resetCharacterAttribute: result = "\(ESC)[0m" case .boldCharacter(let flag): result = "\(ESC)[\(flag ? 1: 22)m" case .underlineCharacter(let flag): result = "\(ESC)[\(flag ? 4: 24)m" case .blinkCharacter(let flag): result = "\(ESC)[\(flag ? 5: 25)m" case .reverseCharacter(let flag): result = "\(ESC)[\(flag ? 7: 27)m" case .foregroundColor(let col): result = "\(ESC)[\(colorToCode(isForeground: true, color: col))m" case .defaultForegroundColor: result = "\(ESC)[39m" case .backgroundColor(let col): result = "\(ESC)[\(colorToCode(isForeground: false, color: col))m" case .defaultBackgroundColor: result = "\(ESC)[49m" case .requestScreenSize: result = "\(ESC)[18;0;0t" case .screenSize(let width, let height): result = "\(ESC)[8;\(height);\(width)t" case .selectAltScreen(let selalt): result = selalt ? "\(ESC)[?47h" : "\(ESC)[?47l" } return result } private func colorToCode(isForeground isfg: Bool, color col: CNColor) -> Int32 { let result: Int32 if isfg { result = col.escapeCode() + 30 } else { result = col.escapeCode() + 40 } return result } public func compare(code src: CNEscapeCode) -> Bool { var result = false switch self { case .string(let s0): switch src { case .string(let s1): result = (s0 == s1) default: break } case .eot: switch src { case .eot: result = true default: break } case .newline: switch src { case .newline: result = true default: break } case .tab: switch src { case .tab: result = true default: break } case .backspace: switch src { case .backspace: result = true default: break } case .delete: switch src { case .delete: result = true default: break } case .cursorUp(let n0): switch src { case .cursorUp(let n1): result = (n0 == n1) default: break } case .cursorDown(let n0): switch src { case .cursorDown(let n1): result = (n0 == n1) default: break } case .cursorForward(let n0): switch src { case .cursorForward(let n1): result = (n0 == n1) default: break } case .cursorBackward(let n0): switch src { case .cursorBackward(let n1): result = (n0 == n1) default: break } case .cursorNextLine(let n0): switch src { case .cursorNextLine(let n1): result = (n0 == n1) default: break } case .cursorPreviousLine(let n0): switch src { case .cursorPreviousLine(let n1): result = (n0 == n1) default: break } case .cursorHolizontalAbsolute(let n0): switch src { case .cursorHolizontalAbsolute(let n1): result = (n0 == n1) default: break } case .saveCursorPosition: switch src { case .saveCursorPosition: result = true default: break } case .restoreCursorPosition: switch src { case .restoreCursorPosition: result = true default: break } case .cursorPosition(let row0, let col0): switch src { case .cursorPosition(let row1, let col1): result = (row0 == row1) && (col0 == col1) default: break } case .eraceFromCursorToEnd: switch src { case .eraceFromCursorToEnd: result = true default: break } case .eraceFromCursorToBegin: switch src { case .eraceFromCursorToBegin: result = true default: break } case .eraceEntireBuffer: switch src { case .eraceEntireBuffer: result = true default: break } case .eraceFromCursorToRight: switch src { case .eraceFromCursorToRight: result = true default: break } case .eraceFromCursorToLeft: switch src { case .eraceFromCursorToLeft: result = true default: break } case .eraceEntireLine: switch src { case .eraceEntireLine: result = true default: break } case .scrollUp: switch src { case .scrollUp: result = true default: break } case .scrollDown: switch src { case .scrollDown: result = true default: break } case .resetAll: switch src { case .resetAll: result = true default: break } case .resetCharacterAttribute: switch src { case .resetCharacterAttribute: result = true default: break } case .boldCharacter(let flag0): switch src { case .boldCharacter(let flag1): result = flag0 == flag1 default: break } case .underlineCharacter(let flag0): switch src { case .underlineCharacter(let flag1): result = flag0 == flag1 default: break } case .blinkCharacter(let flag0): switch src { case .blinkCharacter(let flag1): result = flag0 == flag1 default: break } case .reverseCharacter(let flag0): switch src { case .reverseCharacter(let flag1): result = flag0 == flag1 default: break } case .foregroundColor(let col0): switch src { case .foregroundColor(let col1): result = col0 == col1 default: break } case .defaultForegroundColor: switch src { case .defaultForegroundColor: result = true default: break } case .backgroundColor(let col0): switch src { case .backgroundColor(let col1): result = col0 == col1 default: break } case .defaultBackgroundColor: switch src { case .defaultBackgroundColor: result = true default: break } case .requestScreenSize: switch src { case .requestScreenSize: result = true default: break } case .screenSize(let width0, let height0): switch src { case .screenSize(let width1, let height1): result = (width0 == width1) && (height0 == height1) default: break } case .selectAltScreen(let s0): switch src { case .selectAltScreen(let s1): result = (s0 == s1) default: break } } return result } public enum DecodeResult { case ok(Array<CNEscapeCode>) case error(NSError) } public static func decode(string src: String) -> DecodeResult { do { let strm = CNStringStream(string: src) let result = try decodeString(stream: strm) return .ok(result) } catch { return .error(error as NSError) } } private static func decodeString(stream strm: CNStringStream) throws -> Array<CNEscapeCode> { var result: Array<CNEscapeCode> = [] var substr = "" while !strm.isEmpty() { let c0 = try nextChar(stream: strm) switch c0 { case Character.ESC: /* Save current sub string */ if substr.count > 0 { result.append(CNEscapeCode.string(substr)) substr = "" } /* get next char */ let c1 = try nextChar(stream: strm) switch c1 { case "[": /* Decode escape sequence */ let commands = try decodeEscapeSequence(stream: strm) result.append(contentsOf: commands) case "7": result.append(.saveCursorPosition) case "8": result.append(.restoreCursorPosition) default: result.append(.string("\(c0)\(c1)")) } case Character.LF, Character.CR: /* Save current sub string */ if substr.count > 0 { result.append(CNEscapeCode.string(substr)) substr = "" } /* add newline */ result.append(.newline) case Character.TAB: /* Save current sub string */ if substr.count > 0 { result.append(CNEscapeCode.string(substr)) substr = "" } /* add tab */ result.append(.tab) case Character.BS: /* Save current sub string */ if substr.count > 0 { result.append(CNEscapeCode.string(substr)) substr = "" } /* add backspace */ result.append(.backspace) case Character.DEL: /* Save current sub string */ if substr.count > 0 { result.append(CNEscapeCode.string(substr)) substr = "" } /* add delete */ result.append(.delete) case Character.EOT: /* Save current sub string */ if substr.count > 0 { result.append(CNEscapeCode.string(substr)) substr = "" } /* add delete */ result.append(.eot) default: substr.append(c0) } } /* Unsaved string */ if substr.count > 0 { result.append(CNEscapeCode.string(substr)) substr = "" } return result } private static func decodeEscapeSequence(stream strm: CNStringStream) throws -> Array<CNEscapeCode> { let tokens = try decodeStringToTokens(stream: strm) let tokennum = tokens.count if tokennum == 0 { throw incompleteSequenceError() } var results : Array<CNEscapeCode> = [] let lasttoken = tokens[tokennum - 1] if let c = lasttoken.getSymbol() { switch c { case "A": results.append(CNEscapeCode.cursorUp(try get1Parameter(from: tokens, forCommand: c))) case "B": results.append(CNEscapeCode.cursorDown(try get1Parameter(from: tokens, forCommand: c))) case "C": results.append(CNEscapeCode.cursorForward(try get1Parameter(from: tokens, forCommand: c))) case "D": results.append(CNEscapeCode.cursorBackward(try get1Parameter(from: tokens, forCommand: c))) case "E": results.append(CNEscapeCode.cursorNextLine(try get1Parameter(from: tokens, forCommand: c))) case "F": results.append(CNEscapeCode.cursorPreviousLine(try get1Parameter(from: tokens, forCommand: c))) case "G": results.append(CNEscapeCode.cursorHolizontalAbsolute(try get1Parameter(from: tokens, forCommand: c))) case "H": let (row, col) = try get0Or2Parameter(from: tokens, forCommand: c) results.append(CNEscapeCode.cursorPosition(row, col)) case "J": let param = try get1Parameter(from: tokens, forCommand: c) switch param { case 0: results.append(CNEscapeCode.eraceFromCursorToEnd) case 1: results.append(CNEscapeCode.eraceFromCursorToBegin) case 2: results.append(CNEscapeCode.eraceEntireBuffer) default: throw invalidCommandAndParameterError(command: c, parameter: param) } case "K": let param = try get1Parameter(from: tokens, forCommand: c) switch param { case 0: results.append(CNEscapeCode.eraceFromCursorToRight) case 1: results.append(CNEscapeCode.eraceFromCursorToLeft) case 2: results.append(CNEscapeCode.eraceEntireLine) default: throw invalidCommandAndParameterError(command: c, parameter: param) } case "S": let param = try get1Parameter(from: tokens, forCommand: c) results.append(CNEscapeCode.scrollUp(param)) case "T": let param = try get1Parameter(from: tokens, forCommand: c) results.append(CNEscapeCode.scrollDown(param)) case "h": let param = try getDec1Parameter(from: tokens, forCommand: c) switch param { case 47: results.append(CNEscapeCode.selectAltScreen(true)) // XT_ALTSCRN default: throw invalidCommandAndParameterError(command: c, parameter: param) } case "l": let param = try getDec1Parameter(from: tokens, forCommand: c) switch param { case 47: results.append(CNEscapeCode.selectAltScreen(false)) // XT_ALTSCRN default: throw invalidCommandAndParameterError(command: c, parameter: param) } case "m": let params = try getParameters(from: tokens, count: tokennum - 1, forCommand: c) results.append(contentsOf: try CNEscapeCode.decodeCharacterAttributes(parameters: params)) case "s": results.append(.saveCursorPosition) case "t": let (param0, param1, param2) = try get3Parameter(from: tokens, forCommand: c) switch param0 { case 8: results.append(.screenSize(param2, param1)) case 18: results.append(.requestScreenSize) default: throw invalidCommandAndParameterError(command: c, parameter: param0) } case "u": results.append(.restoreCursorPosition) default: throw unknownCommandError(command: c) } } else { throw incompleteSequenceError() } return results } private static func decodeCharacterAttributes(parameters params: Array<Int>) throws -> Array<CNEscapeCode> { var results: Array<CNEscapeCode> = [] var index: Int = 0 let paramnum = params.count while index < paramnum { let param = params[index] if param == 0 { /* Reset status */ results.append(.resetCharacterAttribute) /* Next index */ index += 1 } else if param == 1 { /* Reset status */ results.append(.boldCharacter(true)) /* Next index */ index += 1 } else if param == 4 { /* Reset status */ results.append(.underlineCharacter(true)) /* Next index */ index += 1 } else if param == 5 { /* Reset status */ results.append(.blinkCharacter(true)) /* Next index */ index += 1 } else if param == 7 { /* Reset status */ results.append(.reverseCharacter(true)) /* Next index */ index += 1 } else if param == 22 { /* Reset status */ results.append(.boldCharacter(false)) /* Next index */ index += 1 } else if param == 24 { /* Reset status */ results.append(.underlineCharacter(false)) /* Next index */ index += 1 } else if param == 25 { /* Reset status */ results.append(.blinkCharacter(false)) /* Next index */ index += 1 } else if param == 27 { /* Reset status */ results.append(.reverseCharacter(false)) /* Next index */ index += 1 } else if 30<=param && param<=37 { if let col = CNColor.color(withEscapeCode: Int32(param - 30)) { results.append(.foregroundColor(col)) } else { throw invalidCommandAndParameterError(command: "m", parameter: param) } /* Next index */ index += 1 } else if param == 39 { results.append(.defaultForegroundColor) /* Next index */ index += 1 } else if 40<=param && param<=47 { if let col = CNColor.color(withEscapeCode: Int32(param - 40)) { results.append(.backgroundColor(col)) } else { throw invalidCommandAndParameterError(command: "m", parameter: param) } /* Next index */ index += 1 } else if param == 49 { results.append(.defaultBackgroundColor) /* Next index */ index += 1 } else { throw invalidCommandAndParameterError(command: "m", parameter: param) } } return results } private static func getParameters(from tokens: Array<CNToken>, count tokennum: Int, forCommand c: Character) throws -> Array<Int> { if tokennum > 0 { var result: Array<Int> = [] for token in tokens[0..<tokennum] { switch token.type { case .IntToken(let val): result.append(val) case .SymbolToken(let c): if c != ";" { throw unexpectedCharacterError(char: c) } default: throw incompleteSequenceError() } } return result } else { return [0] } } private static func get1Parameter(from tokens: Array<CNToken>, forCommand c: Character) throws -> Int { if tokens.count == 1 { return 1 // default value } else if tokens.count == 2 { if let param = tokens[0].getInt() { return param } } throw invalidCommandAndParameterError(command: c, parameter: -1) } private static func get0Or2Parameter(from tokens: Array<CNToken>, forCommand c: Character) throws -> (Int, Int) { if tokens.count == 4 { if let p0 = tokens[0].getInt(), let p1 = tokens[2].getInt() { return (p0, p1) } } else if tokens.count == 1 { return (1, 1) // give default values } throw invalidCommandAndParameterError(command: c, parameter: -1) } private static func get3Parameter(from tokens: Array<CNToken>, forCommand c: Character) throws -> (Int, Int, Int) { if tokens.count == 6 { if let p0 = tokens[0].getInt(), let p1 = tokens[2].getInt(), let p2 = tokens[4].getInt() { return (p0, p1, p2) } } throw invalidCommandAndParameterError(command: c, parameter: -1) } private static func getDec1Parameter(from tokens: Array<CNToken>, forCommand c: Character) throws -> Int { if tokens.count == 3 { if tokens[0].getSymbol() == "?" { if let pm = tokens[1].getInt() { return pm } } } throw invalidCommandAndParameterError(command: c, parameter: -1) } private static func decodeStringToTokens(stream strm: CNStringStream) throws -> Array<CNToken> { var result: Array<CNToken> = [] while !strm.isEmpty() { if let ival = try nextInt(stream: strm) { let newtoken = CNToken(type: .IntToken(ival), lineNo: 0) result.append(newtoken) } else { let c2 = try nextChar(stream: strm) let newtoken = CNToken(type: .SymbolToken(c2), lineNo: 0) result.append(newtoken) /* Finish at the alphabet */ if c2.isLetter { return result } } } return result } private static func nextInt(stream strm: CNStringStream) throws -> Int? { let c0 = try nextChar(stream: strm) if let digit = c0.toInt() { var result = digit var docont = true while docont { let c2 = try nextChar(stream: strm) if let digit = c2.toInt() { result = result * 10 + digit } else { let _ = strm.ungetc() // unget c2 docont = false } } return Int(result) } else { let _ = strm.ungetc() // unget c0 return nil } } private static func nextChar(stream strm: CNStringStream) throws -> Character { if let c = strm.getc() { return c } else { throw incompleteSequenceError() } } private func hex(_ v: Int) -> String { return String(v, radix: 16) } private static func incompleteSequenceError() -> NSError { return NSError.parseError(message: "Incomplete sequence") } private static func unexpectedCharacterError(char c: Character) -> NSError { return NSError.parseError(message: "Unexpected character: \(c)") } private static func unknownCommandError(command cmd: Character) -> NSError { return NSError.parseError(message: "Unknown command: \(cmd)") } private static func invalidCommandAndParameterError(command cmd: Character, parameter param: Int) -> NSError { let paramstr = param > 0 ? ", paramter: \(param)" : "" return NSError.parseError(message: "Invalid command: \(cmd)" + paramstr) } }
lgpl-2.1
715cbdcfe15d69886f0763ae99ce7e95
31.479139
132
0.657509
3.181543
false
false
false
false
MediaArea/MediaInfo
Source/GUI/iOS/MediaInfo/SubscribeViewController.swift
1
9427
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ import UIKit import Foundation import Toast_Swift extension UIButton { func loadingIndicator(_ show: Bool) { let tag = 162411 if show { self.isEnabled = false self.alpha = 0.5 let indicator = UIActivityIndicatorView() let buttonHeight = self.bounds.size.height let buttonWidth = self.bounds.size.width indicator.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2) indicator.tag = tag self.addSubview(indicator) indicator.startAnimating() } else { self.isEnabled = true self.alpha = 1.0 if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView { indicator.stopAnimating() indicator.removeFromSuperview() } } } } protocol SubscribeResultDelegate { func showMessage(message: String?) } class SubscribeViewController: UIViewController { @IBOutlet weak var subscribeText: UILabel! @IBOutlet weak var statusText: UILabel! @IBOutlet weak var subscribeButton: UIButton! @IBOutlet weak var lifetimeSubscribeButton: UIButton! @IBOutlet weak var restoreButton: UIButton! @IBOutlet weak var legalText: UILabel! var message: String? = nil var delegate: SubscribeResultDelegate? = nil var purchasing: Bool = false @IBAction func subscribe(_ sender: Any) { subscribeButton.loadingIndicator(true) purchasing = true SubscriptionManager.shared.purchase(product: SubscriptionManager.shared.subscriptionDetails) } @IBAction func lifetimeSubscribe(_ sender: Any) { lifetimeSubscribeButton.loadingIndicator(true) purchasing = true SubscriptionManager.shared.purchase(product: SubscriptionManager.shared.lifetimeSubscriptionDetails) } @IBAction func restore(_ sender: Any) { SubscriptionManager.shared.restore() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if SubscriptionManager.shared.isLifetime { statusText.text = NSLocalizedString("Lifetime subscription detected.", tableName: "Core", comment: "") } else if let date = SubscriptionManager.shared.subscriptionEndDate { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short if date >= Date() { statusText.text = NSLocalizedString("Subscription active until %DATE%", tableName: "Core", comment: "").replacingOccurrences(of: "%DATE%", with: formatter.string(from: date)) if let short = Calendar.current.date(byAdding: .day, value: 7, to: Date()), short >= date { statusText.textColor = UIColor.orange } else { statusText.textColor = UIColor.green } statusText.sizeToFit() } else { statusText.text = NSLocalizedString("Subscription expired since %DATE%", tableName: "Core", comment: "").replacingOccurrences(of: "%DATE%", with: formatter.string(from: date)) statusText.textColor = UIColor.red statusText.sizeToFit() } } } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Subscribe", tableName: "Core", comment: "") navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Close", tableName: "Core", comment: ""), style: .plain, target: self, action: #selector(close)) navigationController?.isNavigationBarHidden = false subscribeButton.loadingIndicator(true) lifetimeSubscribeButton.loadingIndicator(true) if SubscriptionManager.shared.subscriptionDetails == nil || SubscriptionManager.shared.lifetimeSubscriptionDetails == nil { NotificationCenter.default.addObserver(self, selector: #selector(subscriptionDetailsAviable(_:)), name: .subscriptionDetailsReady, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(subscriptionDetailsAviable(_:)), name: .subscriptionDetailsUnaviable, object: nil) SubscriptionManager.shared.loadSubscription() } else { updateSubscriptionDetails() } NotificationCenter.default.addObserver(self, selector: #selector(purchaseFailed(_:)), name: .purchaseFailed, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(purchaseDeferred(_:)), name: .purchaseDeferred, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(purchaseSucceeded(_:)), name: .purchaseSucceeded, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(purchaseRestored(_:)), name: .restoreFinished, object: nil) } override func viewDidDisappear(_ animated: Bool) { delegate?.showMessage(message: message) } @objc func close() { navigationController?.dismiss(animated: true, completion: nil) } @objc func purchaseFailed(_ notification: Notification) { if (purchasing) { purchasing = false subscribeButton.loadingIndicator(false) lifetimeSubscribeButton.loadingIndicator(false) view.makeToast(NSLocalizedString("Purchase canceled or failed", tableName: "Core", comment: ""), duration: 5.0, position: .top) } } @objc func purchaseDeferred(_ notification: Notification) { if (purchasing) { purchasing = false subscribeButton.loadingIndicator(false) lifetimeSubscribeButton.loadingIndicator(false) view.makeToast(NSLocalizedString("Purchase waiting for parent approval", tableName: "Core", comment: ""), duration: 5.0, position: .top) } } @objc func purchaseSucceeded(_ notification: Notification) { if (purchasing) { purchasing = false subscribeButton.loadingIndicator(false) lifetimeSubscribeButton.loadingIndicator(false) message = NSLocalizedString("Purchase succeeded, thanks for your support!", tableName: "Core", comment: "") close() } } @objc func purchaseRestored(_ notification: Notification) { if SubscriptionManager.shared.isLifetime { message = NSLocalizedString("Purchase restored", tableName: "Core", comment: "") } else { message = NSLocalizedString("No lifetime purchase found", tableName: "Core", comment: "") } } @objc func subscriptionDetailsAviable(_ notification: Notification) { updateSubscriptionDetails() } open func updateSubscriptionDetails() { if let subscriptionDetails = SubscriptionManager.shared.subscriptionDetails, let lifetimeSubscriptionDetails = SubscriptionManager.shared.lifetimeSubscriptionDetails { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = subscriptionDetails.priceLocale if let price = formatter.string(from: subscriptionDetails.price) { subscribeButton.loadingIndicator(false) if SubscriptionManager.shared.subscriptionEndDate != nil { subscribeButton.setTitle(NSLocalizedString("Renew subscription (%PRICE% for one year)", tableName: "Core", comment: "").replacingOccurrences(of: "%PRICE%", with: price), for: .normal) } else { subscribeButton.setTitle(NSLocalizedString("Subscribe %PRICE% for one year", tableName: "Core", comment: "").replacingOccurrences(of: "%PRICE%", with: price), for: .normal) } formatter.locale = lifetimeSubscriptionDetails.priceLocale if let lifetimePrice = formatter.string(from: lifetimeSubscriptionDetails.price) { lifetimeSubscribeButton.loadingIndicator(false) lifetimeSubscribeButton.setTitle(NSLocalizedString("Lifetime subscription for %PRICE%", tableName: "Core", comment: "").replacingOccurrences(of: "%PRICE%", with: lifetimePrice), for: .normal) legalText.text = """ A \(price) renewable or \(lifetimePrice) lifetime purchase will be applied to your iTunes account on confirmation. For a renewable subscription, if a subscription is already active one year will be added to your current subscription end date. """ legalText.sizeToFit() } if SubscriptionManager.shared.isLifetime { subscribeButton.isEnabled = false lifetimeSubscribeButton.isEnabled = false } } else { message = NSLocalizedString("Unable to retrieve subscription details.", tableName: "Core", comment: "") close() } } else { message = NSLocalizedString("Unable to retrieve subscription details.", tableName: "Core", comment: "") close() } } }
bsd-2-clause
1d3d5094c15501b763a2983194caae14
43.890476
211
0.647184
5.452285
false
false
false
false
SmallElephant/FESwiftDemo
12-ShadowDash/12-ShadowDash/ViewController.swift
1
2601
// // ViewController.swift // 12-ShadowDash // // Created by keso on 2017/3/26. // Copyright © 2017年 FlyElephant. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setUp() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: SetUp func setUp() { let view:UIView = UIView.init(frame: CGRect(x: 50, y: 200, width: 50, height: 50)) view.backgroundColor = UIColor.blue view.layer.shadowColor = UIColor.red.cgColor view.layer.shadowOpacity = 1.0 self.view.addSubview(view) let view1:UIView = UIView.init(frame: CGRect(x: 150, y: 200, width: 50, height: 50)) view1.backgroundColor = UIColor.blue view1.layer.shadowColor = UIColor.red.cgColor view1.layer.shadowOpacity = 1.0 view1.layer.shadowOffset = CGSize(width: 0, height: 0) view1.layer.shadowRadius = 4 self.view.addSubview(view1) let view2:UIView = UIView.init(frame: CGRect(x: 250, y: 200, width: 50, height: 50)) view2.backgroundColor = UIColor.blue view2.layer.masksToBounds = true view2.layer.cornerRadius = 25 view2.layer.shadowColor = UIColor.red.cgColor view2.layer.shadowOpacity = 1.0 view2.layer.shadowOffset = CGSize(width: 0, height: 0) view2.layer.shadowRadius = 4 self.view.addSubview(view2) let shadowView:UIView = UIView(frame: CGRect(x: 50, y: 300, width: 50, height: 50)) shadowView.backgroundColor = UIColor.white shadowView.layer.shadowColor = UIColor.red.cgColor shadowView.layer.shadowOpacity = 1.0 shadowView.layer.shadowOffset = CGSize(width: 0, height: 0) shadowView.layer.shadowRadius = 4 shadowView.clipsToBounds = false shadowView.layer.cornerRadius = 25.0 let innerView:UIView = UIView.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) innerView.backgroundColor = UIColor.yellow innerView.clipsToBounds = true innerView.layer.cornerRadius = 25 shadowView.addSubview(innerView) self.view.addSubview(shadowView) } }
mit
552852be23710af4771fbfd714c46dbe
27.866667
92
0.602386
4.410866
false
false
false
false
onebytegone/actionable
Actionable/ActionableTimer.swift
1
2397
// // ActionableTimer.swift // Actionable // // Created by Ethan Smith on 6/15/15. // Copyright (c) 2015 Ethan Smith. All rights reserved. // import Foundation public class ActionableTimer { private var timers: [String : NSTimer] = [:] deinit { disposeOfStoredTimers() } public func timerWithInterval(interval: NSTimeInterval, repeats: Bool = false, key: String? = nil, closure: () -> Void) { // Since the closure passed doesn't take any args, // we are going to wrap it with one that does. let wrapper = { ( arg: Any? ) in closure() } self.timerWithInterval(interval, repeats: repeats, key: key, closure: wrapper, data: nil) } public func timerWithInterval(interval: NSTimeInterval, repeats: Bool = false, key: String? = nil, closure: (Any?) -> Void, data: Any?) { let timer = NSTimer.scheduledTimerWithTimeInterval( interval, target: self, selector: "timerTriggered:", userInfo: TimerInfoPackage(closure: closure, data: data, repeating: repeats), repeats: repeats ) storeTimer(timer, key: key) } public func cancelTimer(key: String) { timers[key]?.invalidate() timers[key] = nil } public func disposeOfStoredTimers() { // Cancel all timers for (key, timer) in timers { cancelTimer(key) } } @objc func timerTriggered(timer: NSTimer) { let package = timer.userInfo as! TimerInfoPackage // If the timer doesn't repeat, cancel it if !package.repeating { let keys = (timers as NSDictionary).allKeysForObject(timer) as! [String] keys.map { (key: String) in self.cancelTimer(key) } } package.closure(package.data) } private func storeTimer(timer: NSTimer, key: String?) { let unwrappedKey = key ?? "\(NSDate.timeIntervalSinceReferenceDate())" // If a timer was already set for this key, kill it cancelTimer(unwrappedKey) timers[unwrappedKey] = timer } func numberOfStoredTimers() -> Int { return timers.count } } private class TimerInfoPackage { var closure: (Any?) -> Void = { _ in } var data: Any? = nil var repeating: Bool = false init(closure: (Any?) -> Void, data: Any?, repeating: Bool) { self.closure = closure self.data = data self.repeating = repeating } }
mit
dba12d826be1826cf70bf3765cb3d0f4
26.551724
140
0.627034
4.118557
false
false
false
false
gu704823/huobanyun
huobanyun/giftview.swift
1
1175
// // giftview.swift // alertview // // Created by AirBook on 2017/6/27. // Copyright © 2017年 swift. All rights reserved. // import UIKit import WebKit //动态图片 class giftview: UIView { //定义 let Screen_width = UIScreen.main.bounds.size.width let Screen_height = UIScreen.main.bounds.size.height var webbgview = WKWebView() init(filename:String){ super.init(frame: CGRect(x: 0, y: Screen_height/1.6+20, width: Screen_width, height: Screen_height)) creatbgview(filename: filename) } fileprivate func creatbgview(filename:String){ let filepatch = Bundle.main.path(forResource: filename, ofType: "gif") let gif = NSData(contentsOfFile: filepatch!)! as Data webbgview = WKWebView(frame: CGRect(x: 0, y: 0, width: Screen_width, height: Screen_height)) let url = NSURL() as URL webbgview.load(gif, mimeType: "image/gif", characterEncodingName: String(), baseURL: url) webbgview.isUserInteractionEnabled = false addSubview(webbgview) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
d894ba6a474302a3615e98239e84240b
32.142857
108
0.663793
3.729904
false
false
false
false
xusader/firefox-ios
Utils/AppConstants.swift
2
1194
/* 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/. */ public struct AppConstants { static var StatusBarHeight: CGFloat { if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact { return 0 } return 20 } static let ToolbarHeight: CGFloat = 44 static let DefaultRowHeight: CGFloat = 58 static let DefaultPadding: CGFloat = 10 static let DefaultMediumFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 13) static let DefaultSmallFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 11) static let DefaultSmallFontBold = UIFont(name: "HelveticaNeue-Bold", size: 11) // These highlight colors are currently only used on Snackbar buttons when they're pressed static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9) static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0) }
mpl-2.0
8ab5422f71597f4bab4004dea7dfc1b5
48.75
136
0.711893
4.294964
false
false
false
false
nRewik/swift-corelibs-foundation
Foundation/NSCalendar.swift
1
73470
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) internal let kCFCalendarUnitEra = CFCalendarUnit.Era.rawValue internal let kCFCalendarUnitYear = CFCalendarUnit.Year.rawValue internal let kCFCalendarUnitMonth = CFCalendarUnit.Month.rawValue internal let kCFCalendarUnitDay = CFCalendarUnit.Day.rawValue internal let kCFCalendarUnitHour = CFCalendarUnit.Hour.rawValue internal let kCFCalendarUnitMinute = CFCalendarUnit.Minute.rawValue internal let kCFCalendarUnitSecond = CFCalendarUnit.Second.rawValue internal let kCFCalendarUnitWeekday = CFCalendarUnit.Weekday.rawValue internal let kCFCalendarUnitWeekdayOrdinal = CFCalendarUnit.WeekdayOrdinal.rawValue internal let kCFCalendarUnitQuarter = CFCalendarUnit.Quarter.rawValue internal let kCFCalendarUnitWeekOfMonth = CFCalendarUnit.WeekOfMonth.rawValue internal let kCFCalendarUnitWeekOfYear = CFCalendarUnit.WeekOfYear.rawValue internal let kCFCalendarUnitYearForWeekOfYear = CFCalendarUnit.YearForWeekOfYear.rawValue internal let kCFDateFormatterNoStyle = CFDateFormatterStyle.NoStyle internal let kCFDateFormatterShortStyle = CFDateFormatterStyle.ShortStyle internal let kCFDateFormatterMediumStyle = CFDateFormatterStyle.MediumStyle internal let kCFDateFormatterLongStyle = CFDateFormatterStyle.LongStyle internal let kCFDateFormatterFullStyle = CFDateFormatterStyle.FullStyle #endif public let NSCalendarIdentifierGregorian: String = "gregorian" public let NSCalendarIdentifierBuddhist: String = "buddhist" public let NSCalendarIdentifierChinese: String = "chinese" public let NSCalendarIdentifierCoptic: String = "coptic" public let NSCalendarIdentifierEthiopicAmeteMihret: String = "ethiopic" public let NSCalendarIdentifierEthiopicAmeteAlem: String = "ethiopic-amete-alem" public let NSCalendarIdentifierHebrew: String = "hebrew" public let NSCalendarIdentifierISO8601: String = "" public let NSCalendarIdentifierIndian: String = "indian" public let NSCalendarIdentifierIslamic: String = "islamic" public let NSCalendarIdentifierIslamicCivil: String = "islamic-civil" public let NSCalendarIdentifierJapanese: String = "japanese" public let NSCalendarIdentifierPersian: String = "persian" public let NSCalendarIdentifierRepublicOfChina: String = "roc" public let NSCalendarIdentifierIslamicTabular: String = "islamic-tbla" public let NSCalendarIdentifierIslamicUmmAlQura: String = "islamic-umalqura" public struct NSCalendarUnit : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let Era = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitEra)) public static let Year = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitYear)) public static let Month = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitMonth)) public static let Day = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitDay)) public static let Hour = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitHour)) public static let Minute = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitMinute)) public static let Second = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitSecond)) public static let Weekday = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitWeekday)) public static let WeekdayOrdinal = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitWeekdayOrdinal)) public static let Quarter = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitQuarter)) public static let WeekOfMonth = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitWeekOfMonth)) public static let WeekOfYear = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitWeekOfYear)) public static let YearForWeekOfYear = NSCalendarUnit(rawValue: UInt(kCFCalendarUnitYearForWeekOfYear)) public static let Nanosecond = NSCalendarUnit(rawValue: UInt(1 << 15)) public static let Calendar = NSCalendarUnit(rawValue: UInt(1 << 20)) public static let TimeZone = NSCalendarUnit(rawValue: UInt(1 << 21)) internal var _cfValue: CFCalendarUnit { #if os(OSX) || os(iOS) return CFCalendarUnit(rawValue: self.rawValue) #else return CFCalendarUnit(self.rawValue) #endif } } public struct NSCalendarOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let WrapComponents = NSCalendarOptions(rawValue: 1 << 0) public static let MatchStrictly = NSCalendarOptions(rawValue: 1 << 1) public static let SearchBackwards = NSCalendarOptions(rawValue: 1 << 2) public static let MatchPreviousTimePreservingSmallerUnits = NSCalendarOptions(rawValue: 1 << 8) public static let MatchNextTimePreservingSmallerUnits = NSCalendarOptions(rawValue: 1 << 9) public static let MatchNextTime = NSCalendarOptions(rawValue: 1 << 10) public static let MatchFirst = NSCalendarOptions(rawValue: 1 << 12) public static let MatchLast = NSCalendarOptions(rawValue: 1 << 13) } public class NSCalendar : NSObject, NSCopying, NSSecureCoding { typealias CFType = CFCalendarRef private var _base = _CFInfo(typeID: CFCalendarGetTypeID()) private var _identifier = UnsafeMutablePointer<Void>() private var _locale = UnsafeMutablePointer<Void>() private var _localeID = UnsafeMutablePointer<Void>() private var _tz = UnsafeMutablePointer<Void>() private var _cal = UnsafeMutablePointer<Void>() internal var _cfObject: CFType { return unsafeBitCast(self, CFCalendarRef.self) } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } static public func supportsSecureCoding() -> Bool { return true } public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public class func currentCalendar() -> NSCalendar { return CFCalendarCopyCurrent()._nsObject } public class func autoupdatingCurrentCalendar() -> NSCalendar { NSUnimplemented() } // tracks changes to user's preferred calendar identifier public /*not inherited*/ init?(identifier calendarIdentifierConstant: String) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, calendarIdentifierConstant._cfObject) { return nil } } public init?(calendarIdentifier ident: String) { super.init() if !_CFCalendarInitWithIdentifier(_cfObject, ident._cfObject) { return nil } } deinit { _CFDeinit(self) } public var calendarIdentifier: String { NSUnimplemented() } /*@NSCopying*/ public var locale: NSLocale? { get { return CFCalendarCopyLocale(_cfObject)._nsObject } set { CFCalendarSetLocale(_cfObject, newValue?._cfObject) } } /*@NSCopying*/ public var timeZone: NSTimeZone { get { return CFCalendarCopyTimeZone(_cfObject)._nsObject } set { CFCalendarSetTimeZone(_cfObject, newValue._cfObject) } } public var firstWeekday: Int { get { return CFCalendarGetFirstWeekday(_cfObject) } set { CFCalendarSetFirstWeekday(_cfObject, CFIndex(newValue)) } } public var minimumDaysInFirstWeek: Int { get { return CFCalendarGetMinimumDaysInFirstWeek(_cfObject) } set { CFCalendarSetMinimumDaysInFirstWeek(_cfObject, CFIndex(newValue)) } } // Methods to return component name strings localized to the calendar's locale private func _symbols(key: CFStringRef) -> [String] { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, _cfObject) let result = (CFDateFormatterCopyProperty(dateFormatter, key) as! CFArrayRef)._swiftObject return result.map { return ($0 as! NSString)._swiftObject } } private func _symbol(key: CFStringRef) -> String { let dateFormatter = CFDateFormatterCreate(kCFAllocatorSystemDefault, locale?._cfObject, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle) CFDateFormatterSetProperty(dateFormatter, kCFDateFormatterCalendarKey, self._cfObject) return (CFDateFormatterCopyProperty(dateFormatter, key) as! CFStringRef)._swiftObject } public var eraSymbols: [String] { return _symbols(kCFDateFormatterEraSymbolsKey) } public var longEraSymbols: [String] { return _symbols(kCFDateFormatterLongEraSymbolsKey) } public var monthSymbols: [String] { return _symbols(kCFDateFormatterMonthSymbolsKey) } public var shortMonthSymbols: [String] { return _symbols(kCFDateFormatterShortMonthSymbolsKey) } public var veryShortMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortMonthSymbolsKey) } public var standaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterStandaloneMonthSymbolsKey) } public var shortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneMonthSymbolsKey) } public var veryShortStandaloneMonthSymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneMonthSymbolsKey) } public var weekdaySymbols: [String] { return _symbols(kCFDateFormatterWeekdaySymbolsKey) } public var shortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortWeekdaySymbolsKey) } public var veryShortWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortWeekdaySymbolsKey) } public var standaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterStandaloneWeekdaySymbolsKey) } public var shortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneWeekdaySymbolsKey) } public var veryShortStandaloneWeekdaySymbols: [String] { return _symbols(kCFDateFormatterVeryShortStandaloneWeekdaySymbolsKey) } public var quarterSymbols: [String] { return _symbols(kCFDateFormatterQuarterSymbolsKey) } public var shortQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortQuarterSymbolsKey) } public var standaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterStandaloneQuarterSymbolsKey) } public var shortStandaloneQuarterSymbols: [String] { return _symbols(kCFDateFormatterShortStandaloneQuarterSymbolsKey) } public var AMSymbol: String { return _symbol(kCFDateFormatterAMSymbolKey) } public var PMSymbol: String { return _symbol(kCFDateFormatterPMSymbolKey) } // Calendrical calculations public func minimumRangeOfUnit(unit: NSCalendarUnit) -> NSRange { let r = CFCalendarGetMinimumRangeOfUnit(self._cfObject, unit._cfValue) if (r.location == kCFNotFound) { return NSMakeRange(NSNotFound, NSNotFound) } return NSMakeRange(r.location, r.length) } public func maximumRangeOfUnit(unit: NSCalendarUnit) -> NSRange { let r = CFCalendarGetMaximumRangeOfUnit(_cfObject, unit._cfValue) if r.location == kCFNotFound { return NSMakeRange(NSNotFound, NSNotFound) } return NSMakeRange(r.location, r.length) } public func rangeOfUnit(smaller: NSCalendarUnit, inUnit larger: NSCalendarUnit, forDate date: NSDate) -> NSRange { let r = CFCalendarGetRangeOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate) if r.location == kCFNotFound { return NSMakeRange(NSNotFound, NSNotFound) } return NSMakeRange(r.location, r.length); } public func ordinalityOfUnit(smaller: NSCalendarUnit, inUnit larger: NSCalendarUnit, forDate date: NSDate) -> Int { return Int(CFCalendarGetOrdinalityOfUnit(_cfObject, smaller._cfValue, larger._cfValue, date.timeIntervalSinceReferenceDate)) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// public func rangeOfUnit(unit: NSCalendarUnit, startDate datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public func rangeOfUnit(unit: NSCalendarUnit, forDate date: NSDate) -> NSDateInterval? { var start: CFAbsoluteTime = 0.0 var ti: CFTimeInterval = 0.0 let res: Bool = withUnsafeMutablePointers(&start, &ti) { startp, tip in return CFCalendarGetTimeRangeOfUnit(_cfObject, unit._cfValue, date.timeIntervalSinceReferenceDate, startp, tip) } if res { return NSDateInterval(start: NSDate(timeIntervalSinceReferenceDate: start), interval: ti) } return nil } private func _convert(component: Int, type: String, inout vector: [Int32], inout compDesc: [Int8]) { if component != NSDateComponentUndefined { vector.append(Int32(component)) compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _convert(comps: NSDateComponents) -> (Array<Int32>, Array<Int8>) { var vector = [Int32]() var compDesc = [Int8]() _convert(comps.era, type: "E", vector: &vector, compDesc: &compDesc) _convert(comps.year, type: "y", vector: &vector, compDesc: &compDesc) _convert(comps.quarter, type: "Q", vector: &vector, compDesc: &compDesc) if comps.weekOfYear != NSDateComponentUndefined { _convert(comps.weekOfYear, type: "w", vector: &vector, compDesc: &compDesc) } else { // _convert(comps.week, type: "^", vector: &vector, compDesc: &compDesc) } _convert(comps.weekOfMonth, type: "W", vector: &vector, compDesc: &compDesc) _convert(comps.yearForWeekOfYear, type: "Y", vector: &vector, compDesc: &compDesc) _convert(comps.weekday, type: "E", vector: &vector, compDesc: &compDesc) _convert(comps.weekdayOrdinal, type: "F", vector: &vector, compDesc: &compDesc) _convert(comps.month, type: "M", vector: &vector, compDesc: &compDesc) _convert(comps.leapMonth ? 1 : 0, type: "L", vector: &vector, compDesc: &compDesc) _convert(comps.day, type: "d", vector: &vector, compDesc: &compDesc) _convert(comps.hour, type: "H", vector: &vector, compDesc: &compDesc) _convert(comps.minute, type: "m", vector: &vector, compDesc: &compDesc) _convert(comps.second, type: "s", vector: &vector, compDesc: &compDesc) _convert(comps.nanosecond, type: "#", vector: &vector, compDesc: &compDesc) compDesc.append(0) return (vector, compDesc) } public func dateFromComponents(comps: NSDateComponents) -> NSDate? { var (vector, compDesc) = _convert(comps) self.timeZone = comps.timeZone ?? timeZone var at: CFAbsoluteTime = 0.0 let res: Bool = withUnsafeMutablePointer(&at) { t in return vector.withUnsafeMutableBufferPointer { (inout vectorBuffer: UnsafeMutableBufferPointer<Int32>) in return _CFCalendarComposeAbsoluteTimeV(_cfObject, t, compDesc, vectorBuffer.baseAddress, Int32(vector.count)) } } if res { return NSDate(timeIntervalSinceReferenceDate: at) } else { return nil } } private func _setup(unitFlags: NSCalendarUnit, field: NSCalendarUnit, type: String, inout compDesc: [Int8]) { if unitFlags.contains(field) { compDesc.append(Int8(type.utf8[type.utf8.startIndex])) } } private func _setup(unitFlags: NSCalendarUnit) -> [Int8] { var compDesc = [Int8]() _setup(unitFlags, field: .Era, type: "G", compDesc: &compDesc) _setup(unitFlags, field: .Year, type: "y", compDesc: &compDesc) _setup(unitFlags, field: .Quarter, type: "Q", compDesc: &compDesc) _setup(unitFlags, field: .Month, type: "M", compDesc: &compDesc) _setup(unitFlags, field: .Month, type: "l", compDesc: &compDesc) _setup(unitFlags, field: .Day, type: "d", compDesc: &compDesc) _setup(unitFlags, field: .WeekOfYear, type: "w", compDesc: &compDesc) _setup(unitFlags, field: .WeekOfMonth, type: "W", compDesc: &compDesc) _setup(unitFlags, field: .YearForWeekOfYear, type: "Y", compDesc: &compDesc) _setup(unitFlags, field: .Weekday, type: "E", compDesc: &compDesc) _setup(unitFlags, field: .WeekdayOrdinal, type: "F", compDesc: &compDesc) _setup(unitFlags, field: .Hour, type: "H", compDesc: &compDesc) _setup(unitFlags, field: .Minute, type: "m", compDesc: &compDesc) _setup(unitFlags, field: .Second, type: "s", compDesc: &compDesc) _setup(unitFlags, field: .Nanosecond, type: "#", compDesc: &compDesc) compDesc.append(0) return compDesc } private func _setComp(unitFlags: NSCalendarUnit, field: NSCalendarUnit, vector: [Int32], inout compIndex: Int, setter: (Int32) -> Void) { if unitFlags.contains(field) { setter(vector[compIndex]) compIndex += 1 } } private func _components(unitFlags: NSCalendarUnit, vector: [Int32]) -> NSDateComponents { var compIdx = 0 let comps = NSDateComponents() _setComp(unitFlags, field: .Era, vector: vector, compIndex: &compIdx) { comps.era = Int($0) } _setComp(unitFlags, field: .Year, vector: vector, compIndex: &compIdx) { comps.year = Int($0) } _setComp(unitFlags, field: .Quarter, vector: vector, compIndex: &compIdx) { comps.quarter = Int($0) } _setComp(unitFlags, field: .Month, vector: vector, compIndex: &compIdx) { comps.month = Int($0) } _setComp(unitFlags, field: .Month, vector: vector, compIndex: &compIdx) { comps.leapMonth = $0 != 0 } _setComp(unitFlags, field: .Day, vector: vector, compIndex: &compIdx) { comps.day = Int($0) } _setComp(unitFlags, field: .WeekOfYear, vector: vector, compIndex: &compIdx) { comps.weekOfYear = Int($0) } _setComp(unitFlags, field: .WeekOfMonth, vector: vector, compIndex: &compIdx) { comps.weekOfMonth = Int($0) } _setComp(unitFlags, field: .YearForWeekOfYear, vector: vector, compIndex: &compIdx) { comps.yearForWeekOfYear = Int($0) } _setComp(unitFlags, field: .Weekday, vector: vector, compIndex: &compIdx) { comps.weekday = Int($0) } _setComp(unitFlags, field: .WeekdayOrdinal, vector: vector, compIndex: &compIdx) { comps.weekdayOrdinal = Int($0) } _setComp(unitFlags, field: .Hour, vector: vector, compIndex: &compIdx) { comps.hour = Int($0) } _setComp(unitFlags, field: .Minute, vector: vector, compIndex: &compIdx) { comps.minute = Int($0) } _setComp(unitFlags, field: .Second, vector: vector, compIndex: &compIdx) { comps.second = Int($0) } _setComp(unitFlags, field: .Nanosecond, vector: vector, compIndex: &compIdx) { comps.nanosecond = Int($0) } if unitFlags.contains(.Calendar) { comps.calendar = self } if unitFlags.contains(.TimeZone) { comps.timeZone = timeZone } return comps } /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil public func components(unitFlags: NSCalendarUnit, fromDate date: NSDate) -> NSDateComponents? { let compDesc = _setup(unitFlags) // _CFCalendarDecomposeAbsoluteTimeV requires a bit of a funky vector layout; which does not express well in swift; this is the closest I can come up with to the required format // int32_t ints[20]; // int32_t *vector[20] = {&ints[0], &ints[1], &ints[2], &ints[3], &ints[4], &ints[5], &ints[6], &ints[7], &ints[8], &ints[9], &ints[10], &ints[11], &ints[12], &ints[13], &ints[14], &ints[15], &ints[16], &ints[17], &ints[18], &ints[19]}; var ints = [Int32](count: 20, repeatedValue: 0) let res = ints.withUnsafeMutableBufferPointer { (inout intArrayBuffer: UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in intArrayBuffer.baseAddress.advancedBy(idx) } return vector.withUnsafeMutableBufferPointer { (inout vecBuffer: UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in return _CFCalendarDecomposeAbsoluteTimeV(_cfObject, date.timeIntervalSinceReferenceDate, compDesc, vecBuffer.baseAddress, Int32(compDesc.count - 1)) } } if res { return _components(unitFlags, vector: ints) } return nil } public func dateByAddingComponents(comps: NSDateComponents, toDate date: NSDate, options opts: NSCalendarOptions) -> NSDate? { var (vector, compDesc) = _convert(comps) var at: CFAbsoluteTime = 0.0 let res: Bool = withUnsafeMutablePointer(&at) { t in return vector.withUnsafeMutableBufferPointer { (inout vectorBuffer: UnsafeMutableBufferPointer<Int32>) in return _CFCalendarAddComponentsV(_cfObject, t, CFOptionFlags(opts.rawValue), compDesc, vectorBuffer.baseAddress, Int32(vector.count)) } } if res { return NSDate(timeIntervalSinceReferenceDate: at) } return nil } public func components(unitFlags: NSCalendarUnit, fromDate startingDate: NSDate, toDate resultDate: NSDate, options opts: NSCalendarOptions) -> NSDateComponents { let compDesc = _setup(unitFlags) var ints = [Int32](count: 20, repeatedValue: 0) let res = ints.withUnsafeMutableBufferPointer { (inout intArrayBuffer: UnsafeMutableBufferPointer<Int32>) -> Bool in var vector: [UnsafeMutablePointer<Int32>] = (0..<20).map { idx in return intArrayBuffer.baseAddress.advancedBy(idx) } return vector.withUnsafeMutableBufferPointer { (inout vecBuffer: UnsafeMutableBufferPointer<UnsafeMutablePointer<Int32>>) in _CFCalendarGetComponentDifferenceV(_cfObject, startingDate.timeIntervalSinceReferenceDate, resultDate.timeIntervalSinceReferenceDate, CFOptionFlags(opts.rawValue), compDesc, vecBuffer.baseAddress, Int32(vector.count)) return false } } if res { return _components(unitFlags, vector: ints) } fatalError() } /* This API is a convenience for getting era, year, month, and day of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ public func getEra(eraValuePointer: UnsafeMutablePointer<Int>, year yearValuePointer: UnsafeMutablePointer<Int>, month monthValuePointer: UnsafeMutablePointer<Int>, day dayValuePointer: UnsafeMutablePointer<Int>, fromDate date: NSDate) { if let comps = components([.Era, .Year, .Month, .Day], fromDate: date) { if eraValuePointer != nil { eraValuePointer.memory = comps.era } if yearValuePointer != nil { yearValuePointer.memory = comps.year } if monthValuePointer != nil { monthValuePointer.memory = comps.month } if dayValuePointer != nil { dayValuePointer.memory = comps.day } } } /* This API is a convenience for getting era, year for week-of-year calculations, week of year, and weekday of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ public func getEra(eraValuePointer: UnsafeMutablePointer<Int>, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>, weekday weekdayValuePointer: UnsafeMutablePointer<Int>, fromDate date: NSDate) { if let comps = components([.Era, .YearForWeekOfYear, .WeekOfYear, .Weekday], fromDate: date) { if eraValuePointer != nil { eraValuePointer.memory = comps.era } if yearValuePointer != nil { yearValuePointer.memory = comps.yearForWeekOfYear } if weekValuePointer != nil { weekValuePointer.memory = comps.weekOfYear } if weekdayValuePointer != nil { weekdayValuePointer.memory = comps.weekday } } } /* This API is a convenience for getting hour, minute, second, and nanoseconds of a given date. Pass NULL for a NSInteger pointer parameter if you don't care about that value. */ public func getHour(hourValuePointer: UnsafeMutablePointer<Int>, minute minuteValuePointer: UnsafeMutablePointer<Int>, second secondValuePointer: UnsafeMutablePointer<Int>, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>, fromDate date: NSDate) { if let comps = components([.Hour, .Minute, .Second, .Nanosecond], fromDate: date) { if hourValuePointer != nil { hourValuePointer.memory = comps.hour } if minuteValuePointer != nil { minuteValuePointer.memory = comps.minute } if secondValuePointer != nil { secondValuePointer.memory = comps.second } if nanosecondValuePointer != nil { nanosecondValuePointer.memory = comps.nanosecond } } } /* Get just one component's value. */ public func component(unit: NSCalendarUnit, fromDate date: NSDate) -> Int { let comps = components(unit, fromDate: date) if let res = comps?.valueForComponent(unit) { return res } else { return NSDateComponentUndefined } } /* Create a date with given components. Current era is assumed. */ public func dateWithEra(eraValue: Int, year yearValue: Int, month monthValue: Int, day dayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> NSDate? { let comps = NSDateComponents() comps.era = eraValue comps.year = yearValue comps.month = monthValue comps.day = dayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return dateFromComponents(comps) } /* Create a date with given components. Current era is assumed. */ public func dateWithEra(eraValue: Int, yearForWeekOfYear yearValue: Int, weekOfYear weekValue: Int, weekday weekdayValue: Int, hour hourValue: Int, minute minuteValue: Int, second secondValue: Int, nanosecond nanosecondValue: Int) -> NSDate? { let comps = NSDateComponents() comps.era = eraValue comps.yearForWeekOfYear = yearValue comps.weekOfYear = weekValue comps.weekday = weekdayValue comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue comps.nanosecond = nanosecondValue return dateFromComponents(comps) } /* This API returns the first moment date of a given date. Pass in [NSDate date], for example, if you want the start of "today". If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist. */ public func startOfDayForDate(date: NSDate) -> NSDate { return rangeOfUnit(.Day, forDate: date)!.start } /* This API returns all the date components of a date, as if in a given time zone (instead of the receiving calendar's time zone). The time zone overrides the time zone of the NSCalendar for the purposes of this calculation. Note: if you want "date information in a given time zone" in order to display it, you should use NSDateFormatter to format the date. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// The Darwin version is not nullable but this one is since the conversion from the date and unit flags can potentially return nil public func componentsInTimeZone(timezone: NSTimeZone, fromDate date: NSDate) -> NSDateComponents? { let oldTz = self.timeZone self.timeZone = timezone let comps = components([.Era, .Year, .Month, .Day, .Hour, .Minute, .Second, .Nanosecond, .Weekday, .WeekdayOrdinal, .Quarter, .WeekOfMonth, .WeekOfYear, .YearForWeekOfYear, .Calendar, .TimeZone], fromDate: date) self.timeZone = oldTz return comps } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units, otherwise either less than or greater than. */ public func compareDate(date1: NSDate, toDate date2: NSDate, toUnitGranularity unit: NSCalendarUnit) -> NSComparisonResult { switch (unit) { case NSCalendarUnit.Calendar: return .OrderedSame case NSCalendarUnit.TimeZone: return .OrderedSame case NSCalendarUnit.Day: fallthrough case NSCalendarUnit.Hour: let range = rangeOfUnit(unit, forDate: date1) let ats = range!.start.timeIntervalSinceReferenceDate let at2 = date2.timeIntervalSinceReferenceDate if ats <= at2 && at2 < ats + range!.interval { return .OrderedSame } if at2 < ats { return .OrderedDescending } return .OrderedAscending case NSCalendarUnit.Minute: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(int1 / 60.0) int2 = floor(int2 / 60.0) if int1 == int2 { return .OrderedSame } if int2 < int1 { return .OrderedDescending } return .OrderedAscending case NSCalendarUnit.Second: var int1 = 0.0 var int2 = 0.0 modf(date1.timeIntervalSinceReferenceDate, &int1) modf(date2.timeIntervalSinceReferenceDate, &int2) if int1 == int2 { return .OrderedSame } if int2 < int1 { return .OrderedDescending } return .OrderedAscending case NSCalendarUnit.Nanosecond: var int1 = 0.0 var int2 = 0.0 let frac1 = modf(date1.timeIntervalSinceReferenceDate, &int1) let frac2 = modf(date2.timeIntervalSinceReferenceDate, &int2) int1 = floor(frac1 * 1000000000.0) int2 = floor(frac2 * 1000000000.0) if int1 == int2 { return .OrderedSame } if int2 < int1 { return .OrderedDescending } return .OrderedAscending default: break } let calendarUnits1: [NSCalendarUnit] = [.Era, .Year, .Month, .Day] let calendarUnits2: [NSCalendarUnit] = [.Era, .Year, .Month, .WeekdayOrdinal, .Day] let calendarUnits3: [NSCalendarUnit] = [.Era, .Year, .Month, .WeekOfMonth, .Weekday] let calendarUnits4: [NSCalendarUnit] = [.Era, .YearForWeekOfYear, .WeekOfYear, .Weekday] var units: [NSCalendarUnit] if unit == .YearForWeekOfYear || unit == .WeekOfYear { units = calendarUnits4 } else if unit == .WeekdayOrdinal { units = calendarUnits2 } else if unit == .Weekday || unit == .WeekOfMonth { units = calendarUnits3 } else { units = calendarUnits1 } // TODO: verify that the return value here is never going to be nil; it seems like it may - thusly making the return value here optional which would result in sadness and regret let reducedUnits = units.reduce(NSCalendarUnit()) { $0.union($1) } let comp1 = components(reducedUnits, fromDate: date1)! let comp2 = components(reducedUnits, fromDate: date2)! for unit in units { let value1 = comp1.valueForComponent(unit) let value2 = comp2.valueForComponent(unit) if value1 > value2 { return .OrderedDescending } else if value1 < value2 { return .OrderedAscending } if unit == .Month && calendarIdentifier == kCFCalendarIdentifierChinese._swiftObject { let leap1 = comp1.leapMonth let leap2 = comp2.leapMonth if !leap1 && leap2 { return .OrderedAscending } else if leap1 && !leap2 { return .OrderedDescending } } if unit == reducedUnits { return .OrderedSame } } return .OrderedSame } /* This API compares the given dates down to the given unit, reporting them equal if they are the same in the given unit and all larger units. */ public func isDate(date1: NSDate, equalToDate date2: NSDate, toUnitGranularity unit: NSCalendarUnit) -> Bool { return compareDate(date1, toDate: date2, toUnitGranularity: unit) == .OrderedSame } /* This API compares the Days of the given dates, reporting them equal if they are in the same Day. */ public func isDate(date1: NSDate, inSameDayAsDate date2: NSDate) -> Bool { return compareDate(date1, toDate: date2, toUnitGranularity: .Day) == .OrderedSame } /* This API reports if the date is within "today". */ public func isDateInToday(date: NSDate) -> Bool { return compareDate(date, toDate: NSDate(), toUnitGranularity: .Day) == .OrderedSame } /* This API reports if the date is within "yesterday". */ public func isDateInYesterday(date: NSDate) -> Bool { if let interval = rangeOfUnit(.Day, forDate: NSDate()) { let inYesterday = interval.start.dateByAddingTimeInterval(-60.0) return compareDate(date, toDate: inYesterday, toUnitGranularity: .Day) == .OrderedSame } else { return false } } /* This API reports if the date is within "tomorrow". */ public func isDateInTomorrow(date: NSDate) -> Bool { if let interval = rangeOfUnit(.Day, forDate: NSDate()) { let inTomorrow = interval.end.dateByAddingTimeInterval(60.0) return compareDate(date, toDate: inTomorrow, toUnitGranularity: .Day) == .OrderedSame } else { return false } } /* This API reports if the date is within a weekend period, as defined by the calendar and calendar's locale. */ public func isDateInWeekend(date: NSDate) -> Bool { return _CFCalendarIsWeekend(_cfObject, date.timeIntervalSinceReferenceDate) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// public func rangeOfWeekendStartDate(datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, containingDate date: NSDate) -> Bool /// which is not implementable on Linux due to the lack of being able to properly implement AutoreleasingUnsafeMutablePointer. /// Find the range of the weekend around the given date, returned via two by-reference parameters. /// Returns nil if the given date is not in a weekend. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public func rangeOfWeekendContaining(date: NSDate) -> NSDateInterval? { if let next = nextWeekendAfter(date, options: []) { if let prev = nextWeekendAfter(next.start, options: .SearchBackwards) { if prev.start.timeIntervalSinceReferenceDate <= date.timeIntervalSinceReferenceDate && date.timeIntervalSinceReferenceDate <= prev.end.timeIntervalSinceReferenceDate { return prev } } } return nil } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// public func nextWeekendStartDate(datep: AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: UnsafeMutablePointer<NSTimeInterval>, options: NSCalendarOptions, afterDate date: NSDate) -> Bool /// Returns the range of the next weekend, via two by-reference parameters, which starts strictly after the given date. /// The .SearchBackwards option can be used to find the previous weekend range strictly before the date. /// Returns nil if there are no such things as weekend in the calendar and its locale. /// - Note: A given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a Day in some calendars and locales. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future public func nextWeekendAfter(date: NSDate, options: NSCalendarOptions) -> NSDateInterval? { var range = _CFCalendarWeekendRange() let res = withUnsafeMutablePointer(&range) { rangep in return _CFCalendarGetNextWeekend(_cfObject, rangep) } if res { let comp = NSDateComponents() comp.weekday = range.start if let nextStart = nextDateAfterDate(date, matchingComponents: comp, options: options.union(.MatchNextTime)) { let start = nextStart.dateByAddingTimeInterval(range.onsetTime) comp.weekday = range.end if let nextEnd = nextDateAfterDate(date, matchingComponents: comp, options: options.union(.MatchNextTime)) { var end = nextEnd if end.compare(start) == .OrderedAscending { if let nextOrderedEnd = nextDateAfterDate(end, matchingComponents: comp, options: options.union(.MatchNextTime)) { end = nextOrderedEnd } else { return nil } } if range.ceaseTime > 0 { end = end.dateByAddingTimeInterval(range.ceaseTime) } else { if let dayEnd = rangeOfUnit(.Day, forDate: end) { end = startOfDayForDate(dayEnd.end) } else { return nil } } return NSDateInterval(start: start, end: end) } } } return nil } /* This API returns the difference between two dates specified as date components. For units which are not specified in each NSDateComponents, but required to specify an absolute date, the base value of the unit is assumed. For example, for an NSDateComponents with just a Year and a Month specified, a Day of 1, and an Hour, Minute, Second, and Nanosecond of 0 are assumed. Calendrical calculations with unspecified Year or Year value prior to the start of a calendar are not advised. For each date components object, if its time zone property is set, that time zone is used for it; if the calendar property is set, that is used rather than the receiving calendar, and if both the calendar and time zone are set, the time zone property value overrides the time zone of the calendar property. No options are currently defined; pass 0. */ public func components(unitFlags: NSCalendarUnit, fromDateComponents startingDateComp: NSDateComponents, toDateComponents resultDateComp: NSDateComponents, options: NSCalendarOptions) -> NSDateComponents? { var startDate: NSDate? var toDate: NSDate? if let startCalendar = startingDateComp.calendar { startDate = startCalendar.dateFromComponents(startingDateComp) } else { startDate = dateFromComponents(startingDateComp) } if let toCalendar = resultDateComp.calendar { toDate = toCalendar.dateFromComponents(resultDateComp) } else { toDate = dateFromComponents(resultDateComp) } if let start = startDate { if let end = toDate { return components(unitFlags, fromDate: start, toDate: end, options: options) } } return nil } /* This API returns a new NSDate object representing the date calculated by adding an amount of a specific component to a given date. The NSCalendarWrapComponents option specifies if the component should be incremented and wrap around to zero/one on overflow, and should not cause higher units to be incremented. */ public func dateByAddingUnit(unit: NSCalendarUnit, value: Int, toDate date: NSDate, options: NSCalendarOptions) -> NSDate? { let comps = NSDateComponents() comps.setValue(value, forComponent: unit) return dateByAddingComponents(comps, toDate: date, options: options) } /* This method computes the dates which match (or most closely match) a given set of components, and calls the block once for each of them, until the enumeration is stopped. There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result. If the NSCalendarSearchBackwards option is used, this method finds the previous match before the given date. The intent is that the same matches as for a forwards search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards). If the NSCalendarMatchStrictly option is used, the algorithm travels as far forward or backward as necessary looking for a match, but there are ultimately implementation-defined limits in how far distant the search will go. If the NSCalendarMatchStrictly option is not specified, the algorithm searches up to the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument. If you want to find the next Feb 29 in the Gregorian calendar, for example, you have to specify the NSCalendarMatchStrictly option to guarantee finding it. If an exact match is not possible, and requested with the NSCalendarMatchStrictly option, nil is passed to the block and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.) If the NSCalendarMatchStrictly option is NOT used, exactly one option from the set {NSCalendarMatchPreviousTimePreservingSmallerUnits, NSCalendarMatchNextTimePreservingSmallerUnits, NSCalendarMatchNextTime} must be specified, or an illegal argument exception will be thrown. If the NSCalendarMatchPreviousTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the previous existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 1:37am, if that exists). If the NSCalendarMatchNextTimePreservingSmallerUnits option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing value of the missing unit and preserves the lower units' values (e.g., no 2:37am results in 3:37am, if that exists). If the NSCalendarMatchNextTime option is specified, and there is no matching time before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the next existing time which exists (e.g., no 2:37am results in 3:00am, if that exists). If the NSCalendarMatchFirst option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the first occurrence. If the NSCalendarMatchLast option is specified, and there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher unit to the highest specified unit in the NSDateComponents argument, the method will return the last occurrence. If neither the NSCalendarMatchFirst or NSCalendarMatchLast option is specified, the default behavior is to act as if NSCalendarMatchFirst was specified. There is no option to return middle occurrences of more than two occurrences of a matching time, if such exist. Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the NSDateComponents matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers). The enumeration is stopped by setting *stop = YES in the block and return. It is not necessary to set *stop to NO to keep the enumeration going. */ public func enumerateDatesStartingAfterDate(start: NSDate, matchingComponents comps: NSDateComponents, options opts: NSCalendarOptions, usingBlock block: (NSDate?, Bool, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } /* This method computes the next date which matches (or most closely matches) a given set of components. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ public func nextDateAfterDate(date: NSDate, matchingComponents comps: NSDateComponents, options: NSCalendarOptions) -> NSDate? { var result: NSDate? enumerateDatesStartingAfterDate(date, matchingComponents: comps, options: options) { date, exactMatch, stop in result = date stop.memory = true } return result } /* This API returns a new NSDate object representing the date found which matches a specific component value. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ public func nextDateAfterDate(date: NSDate, matchingUnit unit: NSCalendarUnit, value: Int, options: NSCalendarOptions) -> NSDate? { let comps = NSDateComponents() comps.setValue(value, forComponent: unit) return nextDateAfterDate(date, matchingComponents: comps, options: options) } /* This API returns a new NSDate object representing the date found which matches the given hour, minute, and second values. The general semantics follow those of the -enumerateDatesStartingAfterDate:... method above. To compute a sequence of results, use the -enumerateDatesStartingAfterDate:... method above, rather than looping and calling this method with the previous loop iteration's result. */ public func nextDateAfterDate(date: NSDate, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: NSCalendarOptions) -> NSDate? { let comps = NSDateComponents() comps.hour = hourValue comps.minute = minuteValue comps.second = secondValue return nextDateAfterDate(date, matchingComponents: comps, options: options) } /* This API returns a new NSDate object representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the unit already has that value, this may result in a date which is the same as the given date. Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well. If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other units to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year. The specific behaviors here are as yet unspecified; for example, if I change the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? A likely rule is that the algorithm will try to produce a result which is in the next-larger unit to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For forwards or backwards behavior, one can use the -nextDateAfterDate:matchingUnit:value:options: method above. */ public func dateBySettingUnit(unit: NSCalendarUnit, value v: Int, ofDate date: NSDate, options opts: NSCalendarOptions) -> NSDate? { let currentValue = component(unit, fromDate: date) if currentValue == v { return date } let targetComp = NSDateComponents() targetComp.setValue(v, forComponent: unit) var result: NSDate? enumerateDatesStartingAfterDate(date, matchingComponents: targetComp, options: .MatchNextTime) { date, match, stop in result = date stop.memory = true } return result } /* This API returns a new NSDate object representing the date calculated by setting hour, minute, and second to a given time. If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date). The intent is to return a date on the same day as the original date argument. This may result in a date which is earlier than the given date, of course. */ public func dateBySettingHour(h: Int, minute m: Int, second s: Int, ofDate date: NSDate, options opts: NSCalendarOptions) -> NSDate? { if let range = rangeOfUnit(.Day, forDate: date) { let comps = NSDateComponents() comps.hour = h comps.minute = m comps.second = s var options: NSCalendarOptions = .MatchNextTime options.unionInPlace(opts.contains(.MatchLast) ? .MatchLast : .MatchFirst) if opts.contains(.MatchStrictly) { options.unionInPlace(.MatchStrictly) } if let result = nextDateAfterDate(range.start.dateByAddingTimeInterval(-0.5), matchingComponents: comps, options: options) { if result.compare(range.start) == .OrderedAscending { return nextDateAfterDate(range.start, matchingComponents: comps, options: options) } return result } } return nil } /* This API returns YES if the date has all the matched components. Otherwise, it returns NO. It is useful to test the return value of the -nextDateAfterDate:matchingUnit:value:options:, to find out if the components were obeyed or if the method had to fudge the result value due to missing time. */ public func date(date: NSDate, matchesComponents components: NSDateComponents) -> Bool { let units: [NSCalendarUnit] = [.Era, .Year, .Month, .Day, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .Quarter, .WeekOfMonth, .WeekOfYear, .YearForWeekOfYear, .Nanosecond] var unitFlags: NSCalendarUnit = [] for unit in units { if components.valueForComponent(unit) != NSDateComponentUndefined { unitFlags.unionInPlace(unit) } } if unitFlags == [] { if components.leapMonthSet { if let comp = self.components(.Month, fromDate: date) { return comp.leapMonth } return false } } if let comp = self.components(unitFlags, fromDate: date) { let tempComp = components.copy() as! NSDateComponents if comp.leapMonthSet && !components.leapMonthSet { tempComp.leapMonth = comp.leapMonth } let nanosecond = comp.valueForComponent(.Nanosecond) if nanosecond != NSDateComponentUndefined { if labs(nanosecond - tempComp.valueForComponent(.Nanosecond)) > 500 { return false } else { comp.nanosecond = 0 tempComp.nanosecond = 0 } return tempComp.isEqual(comp) } } return false } } // This notification is posted through [NSNotificationCenter defaultCenter] // when the system day changes. Register with "nil" as the object of this // notification. If the computer/device is asleep when the day changed, // this will be posted on wakeup. You'll get just one of these if the // machine has been asleep for several days. The definition of "Day" is // relative to the current calendar ([NSCalendar currentCalendar]) of the // process and its locale and time zone. There are no guarantees that this // notification is received by observers in a "timely" manner, same as // with distributed notifications. public let NSCalendarDayChangedNotification: String = "" // NSUnimplemented // This is a just used as an extensible struct, basically; // note that there are two uses: one for specifying a date // via components (some components may be missing, making the // specific date ambiguous), and the other for specifying a // set of component quantities (like, 3 months and 5 hours). // Undefined fields have (or fields can be set to) the value // NSDateComponentUndefined. // NSDateComponents is not responsible for answering questions // about a date beyond the information it has been initialized // with; for example, if you initialize one with May 6, 2004, // and then ask for the weekday, you'll get Undefined, not Thurs. // A NSDateComponents is meaningless in itself, because you need // to know what calendar it is interpreted against, and you need // to know whether the values are absolute values of the units, // or quantities of the units. // When you create a new one of these, all values begin Undefined. public var NSDateComponentUndefined: Int = LONG_MAX public class NSDateComponents : NSObject, NSCopying, NSSecureCoding { internal var _calendar: NSCalendar? internal var _timeZone: NSTimeZone? internal var _values = [Int](count: 19, repeatedValue: NSDateComponentUndefined) public override init() { super.init() } public override var hash: Int { var calHash = 0 if let cal = calendar { calHash = cal.hash } if let tz = timeZone { calHash ^= tz.hash } var y = year if NSDateComponentUndefined == y { y = 0 } var m = month if NSDateComponentUndefined == m { m = 0 } var d = day if NSDateComponentUndefined == d { d = 0 } var h = hour if NSDateComponentUndefined == h { h = 0 } var mm = minute if NSDateComponentUndefined == mm { mm = 0 } var s = second if NSDateComponentUndefined == s { s = 0 } var yy = yearForWeekOfYear if NSDateComponentUndefined == yy { yy = 0 } return calHash + (32832013 * (y + yy) + 2678437 * m + 86413 * d + 3607 * h + 61 * mm + s) + (41 * weekOfYear + 11 * weekOfMonth + 7 * weekday + 3 * weekdayOrdinal + quarter) * (1 << 5) } public override func isEqual(object: AnyObject?) -> Bool { if let other = object as? NSDateComponents { if era != other.era { return false } if year != other.year { return false } if quarter != other.quarter { return false } if month != other.month { return false } if day != other.day { return false } if hour != other.hour { return false } if minute != other.minute { return false } if second != other.second { return false } if nanosecond != other.nanosecond { return false } if weekOfYear != other.weekOfYear { return false } if weekOfMonth != other.weekOfMonth { return false } if yearForWeekOfYear != other.yearForWeekOfYear { return false } if weekday != other.weekday { return false } if weekdayOrdinal != other.weekdayOrdinal { return false } if leapMonth != other.leapMonth { return false } if calendar != other.calendar { return false } if timeZone != other.timeZone { return false } return true } return false } public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } static public func supportsSecureCoding() -> Bool { return true } public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } /*@NSCopying*/ public var calendar: NSCalendar? { get { return _calendar } set { if let val = newValue { _calendar = (val.copy() as! NSCalendar) } else { _calendar = nil } } } /*@NSCopying*/ public var timeZone: NSTimeZone? { get { return _timeZone } set { if let val = newValue { _timeZone = (val.copy() as! NSTimeZone) } else { _timeZone = nil } } } // these all should probably be optionals public var era: Int { get { return _values[0] } set { _values[0] = newValue } } public var year: Int { get { return _values[1] } set { _values[1] = newValue } } public var month: Int { get { return _values[2] } set { _values[2] = newValue } } public var day: Int { get { return _values[3] } set { _values[3] = newValue } } public var hour: Int { get { return _values[4] } set { _values[4] = newValue } } public var minute: Int { get { return _values[5] } set { _values[5] = newValue } } public var second: Int { get { return _values[6] } set { _values[6] = newValue } } public var weekday: Int { get { return _values[8] } set { _values[8] = newValue } } public var weekdayOrdinal: Int { get { return _values[9] } set { _values[9] = newValue } } public var quarter: Int { get { return _values[10] } set { _values[10] = newValue } } public var nanosecond: Int { get { return _values[11] } set { _values[11] = newValue } } public var weekOfYear: Int { get { return _values[12] } set { _values[12] = newValue } } public var weekOfMonth: Int { get { return _values[13] } set { _values[13] = newValue } } public var yearForWeekOfYear: Int { get { return _values[14] } set { _values[14] = newValue } } public var leapMonth: Bool { get { return _values[15] == 1 } set { _values[15] = newValue ? 1 : 0 } } internal var leapMonthSet: Bool { return _values[15] != NSDateComponentUndefined } /*@NSCopying*/ public var date: NSDate? { if let tz = timeZone { calendar?.timeZone = tz } return calendar?.dateFromComponents(self) } /* This API allows one to set a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth properties cannot be set by this method. */ public func setValue(value: Int, forComponent unit: NSCalendarUnit) { switch unit { case NSCalendarUnit.Era: era = value break case NSCalendarUnit.Year: year = value break case NSCalendarUnit.Month: month = value break case NSCalendarUnit.Day: day = value break case NSCalendarUnit.Hour: hour = value break case NSCalendarUnit.Minute: minute = value break case NSCalendarUnit.Second: second = value break case NSCalendarUnit.Nanosecond: nanosecond = value break case NSCalendarUnit.Weekday: weekday = value break case NSCalendarUnit.WeekdayOrdinal: weekdayOrdinal = value break case NSCalendarUnit.Quarter: quarter = value break case NSCalendarUnit.WeekOfMonth: weekOfMonth = value break case NSCalendarUnit.WeekOfYear: weekOfYear = value break case NSCalendarUnit.YearForWeekOfYear: yearForWeekOfYear = value break case NSCalendarUnit.Calendar: print(".Calendar cannot be set via \(__FUNCTION__)") break case NSCalendarUnit.TimeZone: print(".TimeZone cannot be set via \(__FUNCTION__)") break default: break } } /* This API allows one to get the value of a specific component of NSDateComponents, by enum constant value rather than property name. The calendar and timeZone and isLeapMonth property values cannot be gotten by this method. */ public func valueForComponent(unit: NSCalendarUnit) -> Int { switch unit { case NSCalendarUnit.Era: return era case NSCalendarUnit.Year: return year case NSCalendarUnit.Month: return month case NSCalendarUnit.Day: return day case NSCalendarUnit.Hour: return hour case NSCalendarUnit.Minute: return minute case NSCalendarUnit.Second: return second case NSCalendarUnit.Nanosecond: return nanosecond case NSCalendarUnit.Weekday: return weekday case NSCalendarUnit.WeekdayOrdinal: return weekdayOrdinal case NSCalendarUnit.Quarter: return quarter case NSCalendarUnit.WeekOfMonth: return weekOfMonth case NSCalendarUnit.WeekOfYear: return weekOfYear case NSCalendarUnit.YearForWeekOfYear: return yearForWeekOfYear default: break } return NSDateComponentUndefined } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. The calendar property must be set, or NO is returned. */ public var validDate: Bool { if let cal = calendar { return isValidDateInCalendar(cal) } return false } /* Reports whether or not the combination of properties which have been set in the receiver is a date which exists in the calendar. This method is not appropriate for use on NSDateComponents objects which are specifying relative quantities of calendar components. Except for some trivial cases (e.g., 'seconds' should be 0 - 59 in any calendar), this method is not necessarily cheap. If the time zone property is set in the NSDateComponents object, it is used. */ public func isValidDateInCalendar(calendar: NSCalendar) -> Bool { let cal = calendar.copy() as! NSCalendar if let tz = timeZone { cal.timeZone = tz } let ns = nanosecond if ns != NSDateComponentUndefined && 1000 * 1000 * 1000 <= ns { return false } if ns != NSDateComponentUndefined && 0 < ns { nanosecond = 0 } let d = calendar.dateFromComponents(self) if ns != NSDateComponentUndefined && 0 < ns { nanosecond = ns } if let date = d { let all: NSCalendarUnit = [.Era, .Year, .Month, .Day, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .Quarter, .WeekOfMonth, .WeekOfYear, .YearForWeekOfYear] if let comps = calendar.components(all, fromDate: date) { var val = era if val != NSDateComponentUndefined { if comps.era != val { return false } } val = year if val != NSDateComponentUndefined { if comps.year != val { return false } } val = month if val != NSDateComponentUndefined { if comps.month != val { return false } } if leapMonthSet { if comps.leapMonth != leapMonth { return false } } val = day if val != NSDateComponentUndefined { if comps.day != val { return false } } val = hour if val != NSDateComponentUndefined { if comps.hour != val { return false } } val = minute if val != NSDateComponentUndefined { if comps.minute != val { return false } } val = second if val != NSDateComponentUndefined { if comps.second != val { return false } } val = weekday if val != NSDateComponentUndefined { if comps.weekday != val { return false } } val = weekdayOrdinal if val != NSDateComponentUndefined { if comps.weekdayOrdinal != val { return false } } val = quarter if val != NSDateComponentUndefined { if comps.quarter != val { return false } } val = weekOfMonth if val != NSDateComponentUndefined { if comps.weekOfMonth != val { return false } } val = weekOfYear if val != NSDateComponentUndefined { if comps.weekOfYear != val { return false } } val = yearForWeekOfYear if val != NSDateComponentUndefined { if comps.yearForWeekOfYear != val { return false } } return true } } return false } } extension NSCalendar : _CFBridgable { } extension CFCalendarRef : _NSBridgable { typealias NSType = NSCalendar internal var _nsObject: NSType { return unsafeBitCast(self, NSType.self) } }
apache-2.0
9526b147ae1892cbf6c49fdb96a719d1
44.464109
880
0.632789
5.201048
false
false
false
false
deville/hacky-serializer-swift
HackySerializer/Classes/Mirror+Serialization.swift
1
2428
// // Mirror+Serialization.swift // HackySerializer // // Created by Andrii Chernenko on 16/03/16. // Copyright © 2016 Andrii Chernenko. All rights reserved. // fileprivate func serialize(_ value: Any) -> Any { return (value as? HackySerializable)?.serialized ?? Mirror(reflecting: value).serializedSubject } extension Mirror { var serializedSubject: Any { switch self.displayStyle { case .collection?, .set?: return children .map { Mirror(reflecting: $0.value).displayStyle == nil ? $0.value : serialize($0.value) } case .struct?, .class?: var dictionary: [String: Any] = [:] children.forEach { child in guard let key = child.label else { return } let childMirror = Mirror(reflecting: child) let childValueMirror = Mirror(reflecting: child.value) switch (childMirror.displayStyle, childValueMirror.displayStyle) { case (.tuple?, nil): dictionary[key] = childMirror.descendant(1) ?? NSNull() case (.tuple?, .optional?): dictionary[key] = childValueMirror.descendant(0) .map { Mirror(reflecting: $0).displayStyle == .enum ? "\($0)" : $0 } ?? NSNull() case (.tuple?, .enum?): dictionary[key] = childMirror.descendant(1).map { "\($0)" as Any } ?? NSNull() default: dictionary[key] = serialize(value: child.value) } } return dictionary case .optional?: return self.descendant(0) ?? NSNull() case .dictionary?: var dictionary: [String: Any] = [:] children .map { Mirror(reflecting: $0) } .flatMap { guard let key = $0.descendant(1, 0) as? String else { fatalError("Only string keys are supported in dictionaries") } guard let value = $0.descendant(1, 1) else { return nil } let childValueMirror = Mirror(reflecting: value) let unwrappedValue = childValueMirror.displayStyle == nil ? value : serialize(value: value) return (key, unwrappedValue) } .forEach { dictionary[$0] = $1 } return dictionary default: fatalError("serialization failed, \(displayStyle) serialization is not implemented") } } }
mit
f0b51695743de5121b1ff59c79cffecc
28.962963
101
0.563247
4.570621
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/max-dot-product-of-two-subsequences.swift
2
1225
/** * https://leetcode.com/problems/max-dot-product-of-two-subsequences/ * * */ // Date: Thu May 28 17:04:15 PDT 2020 class Solution { /// /// mark[x][y] indicates the maximum dot product ending at x of nums1, and y of nums2. /// To be, or not to be. /// Options at (x, y) /// 1. Just use the product of numbers at x and y. /// 2. Use product of numbers at x and y, plus the max dot product ending with x - 1, and y - 1. /// 3. Not use product of numbers at x and y, if answer at x - 1 and y is greater. /// 4. Not use product of numbers at x and y, if answer at x and y - 1 is greater. /// func maxDotProduct(_ nums1: [Int], _ nums2: [Int]) -> Int { let n = nums1.count let m = nums2.count var mark = Array(repeating: Array(repeating: Int.min, count: m + 1), count: n + 1) for x in 1 ... n { for y in 1 ... m { mark[x][y] = nums1[x - 1] * nums2[y - 1] mark[x][y] += max(0, mark[x - 1][y - 1]) mark[x][y] = max(mark[x - 1][y], mark[x][y]) mark[x][y] = max(mark[x][y], mark[x][y - 1]) } } // print("\(mark)") return mark[n][m] } }
mit
f42209ffeb9b4653ea682d4e7ceaa840
37.28125
100
0.509388
3.141026
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Classes/Controller/CSTabBarPagerController.swift
1
3022
// // Created by Rene Dohan on 9/19/19. // Copyright (c) 2019 Renetik Software. All rights reserved. // import RenetikObjc import Renetik public typealias CSTabBarPagerControllerItem = (item: UITabBarItem, onClick: (@escaping (UIViewController) -> Void) -> Void) public class CSTabBarPagerController: CSMainController, UITabBarDelegate { private let containerView = CSView.construct().background(.clear) public lazy var tabBar = UITabBar(frame: .zero).construct() private var onClicksDictionary = [UITabBarItem: (callback: @escaping (UIViewController) -> Void) -> Void]() private var currentController: UIViewController? private var currentControllerIndex: Int? @discardableResult public func construct(with parent: CSViewController, items: [CSTabBarPagerControllerItem]) -> Self { super.construct(parent) var barButtonItems = [UITabBarItem]() items.forEach { barButtonItems.add($0.item) onClicksDictionary[$0.item] = $0.onClick } tabBar.delegate = self tabBar.items = barButtonItems tabBar.selectedItem = barButtonItems.first items.first.notNil { item in item.onClick { controller in self.show(controller: controller) } } return self } override public func onViewWillAppearFirstTime() { super.onViewWillAppearFirstTime() view.add(view: tabBar).resizeToFit().flexibleTop().matchParentWidth().from(bottom: 0) view.add(view: containerView).matchParent().margin(bottom: 0, from: tabBar) } override public func onViewDidLayout() { super.onViewDidLayout() tabBar.resizeToFit().from(bottom: 0) containerView.margin(bottom: tabBar.topFromBottom) } public func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { if currentControllerIndex == tabBar.selectedIndex { return } onClicksDictionary[item]! { self.show(controller: $0) } } private func show(controller: UIViewController) { currentController.notNil { dismissChild(controller: $0) if currentControllerIndex! < tabBar.selectedIndex { CATransition.create(for: containerView, type: .push, subtype: .fromRight) } else if currentControllerIndex! > tabBar.selectedIndex { CATransition.create(for: containerView, type: .push, subtype: .fromLeft) } } add(controller: controller, to: containerView).view.matchParent() updateBarItemsAndMenu() currentController = controller currentControllerIndex = tabBar.selectedIndex } public func updateTabSelection() { if tabBar.selectedIndex != currentControllerIndex! { tabBar.selectedIndex = currentControllerIndex! } } public func select(item: UITabBarItem) { tabBar.selectedItem = item tabBar(tabBar, didSelect: item) } }
mit
e5257eb5f4b146fea096ba404cec3f47
34.564706
124
0.657512
4.962233
false
false
false
false
HQL-yunyunyun/SinaWeiBo
SinaWeiBo/SinaWeiBo/Class/Model/HQLUserAccount.swift
1
2980
// // HQLUserAccount.swift // SinaWeiBo // // Created by 何启亮 on 16/5/14. // Copyright © 2016年 HQL. All rights reserved. // import Foundation // 对象归档和解档 // 1.对象遵守NSCoding协议:知道对象要保存和解档哪些属性 // 2.调用归档和解档的方法 class HQLUserAccount: NSObject, NSCoding { // ==================MARK: - 属性propery /// token用户授权的唯一票据 var access_token: String? /// access_token的生命周期,单位是秒数, 基本数据类型不能使用?,KVC会找不到 var expires_in: NSTimeInterval = 0{ didSet { expires_date = NSDate(timeIntervalSinceNow: expires_in) } } /// 剩余时间-- date 模式 var expires_date: NSDate? /// 用户标识 var uid: String? /// 用户昵称 var screen_name: String? /// 用户头像: 大图 180 * 180 var avatar_large: String? /** 构造方法 */ init(dict: [String: AnyObject]) { // 要先创建对象 super.init() // kvc赋值 // 对象创建好后才能使用对象的方法, 内部会调用setValue(value: AnyObject?, forKey key: String),每次拿一个key和value调用一次 self.setValuesForKeysWithDictionary(dict) } // 当setValue:forKey:找不到key时会调用setValue:forUndefinedKey:.如果不实现setValue:forUndefinedKey:就会报错 override func setValue(value: AnyObject?, forUndefinedKey key: String) { CZPrint(items: "forUndefinedKey \(key)") } // 打印方法 description属性 override var description: String{ get{ return "用户账户: access_token: \(access_token), expires_in: \(expires_in), uid: \(uid), expiresDate: \(expires_date)" } } // MARK: - 解档---归档 // 解档 required init?(coder aDecoder: NSCoder) { // 因为解档的decodeObjectForKey方法返回的时一个 AnyObject? 的对象, 所以这里需要用as来转换类型 access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_in = aDecoder.decodeDoubleForKey("expires_in") expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate uid = aDecoder.decodeObjectForKey("uid") as? String screen_name = aDecoder.decodeObjectForKey("screen_name") as? String avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String } // 归档 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeDouble(expires_in, forKey: "expires_in") aCoder.encodeObject(expires_date, forKey: "expires_date") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(screen_name, forKey: "screen_name") aCoder.encodeObject(avatar_large, forKey: "avatar_large") } }
apache-2.0
3f8a144c55f7d5468c2b384c81a18bcf
28.551724
127
0.618825
3.925191
false
false
false
false
jawwad/swift-algorithm-club
Count Occurrences/CountOccurrences.swift
10
764
/* Counts the number of times a value appears in an array in O(lg n) time. The array must be sorted from low to high. */ func countOccurrencesOfKey(_ key: Int, inArray a: [Int]) -> Int { func leftBoundary() -> Int { var low = 0 var high = a.count while low < high { let midIndex = low + (high - low)/2 if a[midIndex] < key { low = midIndex + 1 } else { high = midIndex } } return low } func rightBoundary() -> Int { var low = 0 var high = a.count while low < high { let midIndex = low + (high - low)/2 if a[midIndex] > key { high = midIndex } else { low = midIndex + 1 } } return low } return rightBoundary() - leftBoundary() }
mit
6b73175fc231e0bd02e48eb9d8ca0a1d
20.828571
73
0.539267
3.708738
false
false
false
false
wangshengjia/LeeGo
Sources/Core/Composable.swift
1
2990
// // Composable.swift // LeeGo // // Created by Victor WANG on 21/02/16. // // import Foundation protocol Composable { func composite<View>(_ bricks: [Brick], to targetView: View, with layout: Layout) where View: UIView, View: BrickDescribable } extension Composable { internal func composite<View>(_ bricks: [Brick], to targetView: View, with layout: Layout) where View: UIView, View: BrickDescribable { // remove subviews which do not exist anymore in bricks for subview in targetView.subviews { if let oldBrick = subview.currentBrick, !bricks.contains(oldBrick) { subview.removeFromSuperview() } } // filter bricks already exist let filteredBricks = bricks.filter { (subBrick) -> Bool in if let subbricks = targetView.currentBrick?.childBricks, subbricks.contains(subBrick) { for subview in targetView.subviews { if let subbrick2 = subview.currentBrick, subbrick2 == subBrick { return false } } } return true } filteredBricks.forEach { brick in var view: UIView? = nil; if let nibName = brick.nibName, let brickView = Bundle.main.loadNibNamed(nibName, owner: nil, options: nil)?.first as? UIView { view = brickView } else if let targetClass = brick.targetClass as? UIView.Type { view = targetClass.init() } view?.isRoot = false view?.currentBrick = Brick(name: brick.name, targetClass: brick.targetClass, nibName: brick.nibName) if let view = view { targetView.addSubview(view) view.lg_brickDidAwake() } } //TODO: sort brick's subviews to have as same order as bricks var viewsDictionary = [String: UIView]() for subview in targetView.subviews { if let name = subview.currentBrick?.name { viewsDictionary[name] = subview } } viewsDictionary["superview"] = targetView // Remove constraint with identifier (which means not created by system) targetView.removeConstraints(targetView.constraints.filter({ (constraint) -> Bool in if constraint.mode == .subviewsLayout { return true } return false })) // Layout each view with auto layout visual format language as brick. for format in layout.formats { let constraints = NSLayoutConstraint.constraints(withVisualFormat: format, options: layout.options, metrics: layout.metrics.metrics(), views: viewsDictionary) for constraint in constraints { constraint.lg_setIdentifier(with: .subviewsLayout) targetView.addConstraint(constraint) } } } }
mit
aaf5b457cd14ca28938e9dfefabde503
34.595238
170
0.586622
5.016779
false
false
false
false
marselan/patient-records
Patient-Records/Patient-Records/LoginViewController.swift
1
6301
// // LoginViewController.swift // patient_records // // Created by Mariano Arselan on 19/1/17. // Copyright © 2017 Mariano Arselan. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet var username: UITextField! @IBOutlet var password: UITextField! @IBOutlet var statusMessage: UILabel! var currentTextfield : UITextField? = nil @IBAction func textFieldDidBeginEditing(_ sender: UITextField) { print("begin editing") currentTextfield = sender } @IBAction func textFieldDidEndEditing(_ sender: UITextField) { print("end editing") currentTextfield = nil } @IBAction func loginAction(_ sender: Any) { currentTextfield?.resignFirstResponder() let user = username.text let pwd = password.text if user == "" || pwd == "" { return } SendLogin(user!, pwd!) } @IBOutlet var indicator: UIActivityIndicatorView! func startIndicator() { indicator.startAnimating() UIApplication.shared.beginIgnoringInteractionEvents() } func stopIndicator() { indicator.stopAnimating() UIApplication.shared.endIgnoringInteractionEvents() } func SendLogin(_ user: String, _ pwd: String) { startIndicator() let url = URL(string: Config.instance.backendUrl + "/PatientManager/LoginService/login") var request = URLRequest(url: url!) Config.instance.user = user Config.instance.password = pwd request.addValue(user, forHTTPHeaderField: "user") request.addValue(pwd, forHTTPHeaderField: "password") let session = URLSession.shared let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in guard let response = response else { return } switch response.httpStatusCode() { case 200: DispatchQueue.main.async(execute:self.loginDone) case 530: DispatchQueue.main.async(execute:self.loginFailed) default: DispatchQueue.main.async(execute:self.serviceUnavailable) } }) dataTask.resume() } func loginDone() { let url = URL(string: Config.instance.backendUrl + "/PatientManager/StudyService/types") var request = URLRequest(url: url!) request.addValue(Config.instance.user, forHTTPHeaderField: "user") request.addValue(Config.instance.password, forHTTPHeaderField: "password") let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let task = session.dataTask(with: request, completionHandler: self.studyTypesDataReady) task.resume() } func studyTypesDataReady(_ data : Data?, _ response : URLResponse?, _ error : Error?) { guard let json = data else { return } if let response = response as? HTTPURLResponse { switch response.statusCode { case 200: do { let studyTypes = try JSONDecoder().decode([StudyType].self, from: json) StudyTypes.shared.populate(studyTypes) DispatchQueue.main.async(execute: self.studyTypesLoaded) } catch { return } default: return } } } func studyTypesLoaded() { stopIndicator() self.password.text = "" self.statusMessage.isHidden = true let backItem = UIBarButtonItem() backItem.title = "Logout" navigationItem.backBarButtonItem = backItem let storyboard = UIStoryboard(name: "PatientsStoryboard", bundle:nil) let fvc = storyboard.instantiateViewController(withIdentifier: "Patients") self.navigationController!.pushViewController(fvc, animated: true) } func loginFailed() { stopIndicator() self.statusMessage.text = "Please check your details." self.statusMessage.isHidden = false } func serviceUnavailable() { stopIndicator() self.statusMessage.text = "Service is unavailable now." self.statusMessage.isHidden = false } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.09, green: 0.52, blue: 1.0, alpha: 1.0) self.navigationController?.navigationBar.tintColor = .white } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) addKeyboardListener() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) removeKeyboardListener() } func addKeyboardListener() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name:.UIKeyboardDidShow, object:nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(notification:)), name:.UIKeyboardDidHide, object:nil) } func removeKeyboardListener() { NotificationCenter.default.removeObserver(self) } @IBAction func done(_ sender: UITextField) { if currentTextfield === username { self.password.becomeFirstResponder() } else { loginAction(self) } } @objc func keyboardDidShow(notification : Notification) { if let rect = notification.userInfo!["UIKeyboardBoundsUserInfoKey"] as? CGRect { print(rect) if username.isFirstResponder { print("es un textfield") var parentRect = username.superview?.frame parentRect?.size.height += rect.height } } } @objc func keyboardDidHide(notification: Notification) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
gpl-3.0
f6aed37dbd144a4256945d7bca1ca57e
29.731707
142
0.602381
5.348048
false
false
false
false
knehez/edx-app-ios
Source/DiscussionNewPostViewController.swift
1
12151
// // DiscussionNewPostViewController.swift // edX // // Created by Tang, Jeff on 6/1/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit struct DiscussionNewThread { let courseID: String let topicID: String let type: PostThreadType let title: String let rawBody: String } public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate { private var editingStyle : OEXTextStyle { return OEXTextStyle(weight: OEXTextWeight.Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) } public class Environment: NSObject { private let courseDataManager : CourseDataManager private let networkManager : NetworkManager? private weak var router: OEXRouter? public init(courseDataManager : CourseDataManager, networkManager : NetworkManager?, router: OEXRouter?) { self.courseDataManager = courseDataManager self.networkManager = networkManager self.router = router } } private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text private let environment: Environment private let insetsController = ContentInsetsController() @IBOutlet private var scrollView: UIScrollView! @IBOutlet private var backgroundView: UIView! @IBOutlet private var newPostView: UIView! @IBOutlet private var contentTextView: OEXPlaceholderTextView! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl! @IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint! @IBOutlet private var topicButton: UIButton! @IBOutlet private var postDiscussionButton: UIButton! private let courseID: String private let topics = BackedStream<[DiscussionTopic]>() private var selectedTopic: DiscussionTopic? private var viewControllerOption: MenuOptionsViewController? private var selectedThreadType: PostThreadType = .Discussion { didSet { switch selectedThreadType { case .Discussion: self.contentTextView.placeholder = OEXLocalizedString("COURSE_DASHBOARD_DISCUSSION", nil) OEXStyles.sharedStyles().filledPrimaryButtonStyle.applyToButton(postDiscussionButton, withTitle: OEXLocalizedString("POST_DISCUSSION", nil)) case .Question: self.contentTextView.placeholder = OEXLocalizedString("QUESTION", nil) OEXStyles.sharedStyles().filledPrimaryButtonStyle.applyToButton(postDiscussionButton, withTitle: OEXLocalizedString("POST_QUESTION", nil)) } } } public init(environment: Environment, courseID: String, selectedTopic: DiscussionTopic) { self.environment = environment self.courseID = courseID self.selectedTopic = selectedTopic super.init(nibName: nil, bundle: nil) let stream = environment.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func postTapped(sender: AnyObject) { postDiscussionButton.enabled = false // create new thread (post) if let topic = selectedTopic, topicID = topic.id { let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType ?? .Discussion, title: titleTextField.text, rawBody: contentTextView.text) let apiRequest = DiscussionAPI.createNewThread(newThread) environment.networkManager?.taskForRequest(apiRequest) {[weak self] result in self?.navigationController?.popViewControllerAnimated(true) self?.postDiscussionButton.enabled = true } } } override public func viewDidLoad() { super.viewDidLoad() NSBundle.mainBundle().loadNibNamed("DiscussionNewPostView", owner: self, options: nil) view.addSubview(newPostView) newPostView?.snp_makeConstraints {make in make.edges.equalTo(self.view) } self.navigationItem.title = OEXLocalizedString("POST", nil) contentTextView.textContainer.lineFragmentPadding = 0 contentTextView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets contentTextView.typingAttributes = editingStyle.attributes contentTextView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight() contentTextView.layer.cornerRadius = OEXStyles.sharedStyles().boxCornerRadius() contentTextView.layer.masksToBounds = true contentTextView.delegate = self self.view.backgroundColor = OEXStyles.sharedStyles().neutralXLight() let segmentOptions : [(title : String, value : PostThreadType)] = [ (title : OEXLocalizedString("DISCUSSION", nil), value : .Discussion), (title : OEXLocalizedString("QUESTION", nil), value : .Question), ] let options = segmentOptions.withItemIndexes() for option in options { discussionQuestionSegmentedControl.setTitle(option.value.title, forSegmentAtIndex: option.index) } discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in if let segmentedControl = control as? UISegmentedControl, index = control.selectedSegmentIndex { let threadType = segmentOptions[index].value self?.selectedThreadType = threadType } else { assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum") } }, forEvents: UIControlEvents.ValueChanged) titleTextField.placeholder = OEXLocalizedString("TITLE", nil) titleTextField.defaultTextAttributes = editingStyle.attributes BorderStyle(cornerRadius: OEXStyles.sharedStyles().boxCornerRadius(), width: .Size(1), color: OEXStyles.sharedStyles().neutralXLight()).applyToView(topicButton) if let topic = selectedTopic, name = topic.name { let title = NSString.oex_stringWithFormat(OEXLocalizedString("TOPIC", nil), parameters: ["topic": name]) as String topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(title), forState: .Normal) } topicButton.titleEdgeInsets = UIEdgeInsetsMake(0.0, 8.0, 0.0, 0.0) let dropdownLabel = UILabel() let style = OEXTextStyle(weight : .Normal, size: .Base, color: OEXStyles.sharedStyles().neutralBase()) dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(style.withSize(.XSmall)) topicButton.addSubview(dropdownLabel) dropdownLabel.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(topicButton).offset(-5) make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0) } topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in self?.showTopicPicker() }, forEvents: UIControlEvents.TouchUpInside) postDiscussionButton.enabled = false titleTextField.oex_addAction({[weak self] _ in self?.validatePostButton() }, forEvents: .EditingChanged) let tapGesture = UITapGestureRecognizer() tapGesture.addAction {[weak self] _ in self?.contentTextView.resignFirstResponder() self?.titleTextField.resignFirstResponder() } self.newPostView.addGestureRecognizer(tapGesture) self.insetsController.setupInController(self, scrollView: scrollView) // Force setting it to call didSet which is only called out of initialization content self.selectedThreadType = .Discussion } func showTopicPicker() { if self.viewControllerOption != nil { return } let topics = self.topics.value ?? [] self.viewControllerOption = MenuOptionsViewController() self.viewControllerOption?.menuHeight = min((CGFloat)(self.view.frame.height - self.topicButton.frame.minY - self.topicButton.frame.height), MenuOptionsViewController.menuItemHeight * (CGFloat)(topics.count)) self.viewControllerOption?.menuWidth = self.topicButton.frame.size.width self.viewControllerOption?.delegate = self self.viewControllerOption?.options = topics.map { return $0.name ?? "" } self.viewControllerOption?.selectedOptionIndex = self.selectedTopicIndex() self.view.addSubview(self.viewControllerOption!.view) self.viewControllerOption!.view.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(self.topicButton) make.leading.equalTo(self.topicButton) make.top.equalTo(self.topicButton.snp_bottom) make.bottom.equalTo(self.backgroundView.snp_bottom) } self.viewControllerOption?.view.alpha = 0.0 UIView.animateWithDuration(0.3) { self.viewControllerOption?.view.alpha = 1.0 } } private func selectedTopicIndex() -> Int? { return self.topics.value?.firstIndexMatching { return $0.id == selectedTopic?.id } } public func viewTapped(sender: UITapGestureRecognizer) { contentTextView.resignFirstResponder() titleTextField.resignFirstResponder() } public func textViewDidChange(textView: UITextView) { let fixedWidth = textView.frame.size.width let newSize = textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat.max)) if newSize.height >= minBodyTextHeight { bodyTextViewHeightConstraint.constant = ceil(newSize.height) } self.validatePostButton() self.view.setNeedsLayout() } public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool { if let topic = self.topics.value?[index] { return topic.id != nil } else { return false } } func validatePostButton() { self.postDiscussionButton.enabled = !titleTextField.text.isEmpty && !contentTextView.text.isEmpty } func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) { selectedTopic = self.topics.value?[index] // if a topic has at least one child, the topic cannot be selected (its topic id is nil) if let topic = selectedTopic, name = topic.name where topic.id != nil { topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(NSString.oex_stringWithFormat(OEXLocalizedString("TOPIC", nil), parameters: ["topic": name]) as String), forState: .Normal) UIView.animateWithDuration(0.3, animations: { self.viewControllerOption?.view.alpha = 0.0 }, completion: {(finished: Bool) in self.viewControllerOption?.view.removeFromSuperview() self.viewControllerOption = nil }) } } public override func viewDidLayoutSubviews() { self.insetsController.updateInsets() let postFrame = scrollView.convertRect(postDiscussionButton.bounds, fromView:postDiscussionButton) scrollView.contentSize = CGSizeMake(scrollView.bounds.size.width, postFrame.maxY + OEXStyles.sharedStyles().standardHorizontalMargin()) } }
apache-2.0
944b8e0376235e6d5de36f1492de81b1
43.185455
284
0.669904
5.374171
false
false
false
false
stevehe-campray/BSBDJ
BSBDJ/BSBDJ/Essence(精华)/Model/BSBTopic.swift
1
2883
// // BSBTopic.swift // BSBDJ // // Created by hejingjin on 16/6/2. // Copyright © 2016年 baisibudejie. All rights reserved. //段子 import UIKit class BSBTopic: NSObject { /** 帖子id */ var id : NSString = "" /** 名称 */ var name : NSString = "" /** 头像 */ var profile_image:NSString = "" /** 发帖时间 */ var create_time:NSString = "" /** 文字内容 */ var text:NSString = "" /** 顶的数量 */ var ding:NSInteger = 0 /** 踩的数量 */ var cai:NSInteger = 0 /** 转发的数量 */ var repost:NSInteger = 0 /** 评论的数量 */ var comment:NSInteger = 0 /** 是否有加V */ var sina_v : Bool = false /** 视频或者图片宽度 */ var width :CGFloat = 0; /** 视频或者图片高度 */ var height : CGFloat = 0 //小图 var image0 : NSString = "" //大图 var image1 : NSString = "" //中图 var image2 : NSString = "" //声音时长 var voicetime : NSInteger = 0 //播放次数 var playcount : NSInteger = 0 //声音地址 var voiceuri : NSString = "" //视频地址 var videouri : NSString = "" //视频时长 var videotime : NSInteger = 0 var type : NSInteger = 1 var is_gif : Bool = false /** 辅助计算cell高度 */ var cellHeight : CGFloat = 0; var commentH : CGFloat = 0//最热评论高度 /** 图片的frame*/ var topicpicimageFrame : CGRect = CGRectMake(0, 0, 0, 0) var topicvoiceimageFrame : CGRect = CGRectMake(0, 0, 0, 0) var topicvoideimageFrame : CGRect = CGRectMake(0, 0, 0, 0) var top_cmt : [BSBComment] = [] // private var tagarray : [BSBTagInfo] = [] //字典数组转模型数组 class func dict2Model(list: [[String: AnyObject]]) -> [BSBTopic] { var models = [BSBTopic]() for dict in list { models.append(BSBTopic(dict: dict)) } return models } // setValuesForKeysWithDictionary内部会调用以下方法 override func setValue(value: AnyObject?, forKey key: String) { // 1.判断当前是否正在给微博字典中的user字典赋值 if "top_cmt" == key { // 2.根据user key对应的字典创建一个模型 top_cmt = BSBComment.dict2Model(value as! [[String : AnyObject]]) return } // 3,调用父类方法, 按照系统默认处理 super.setValue(value, forKey: key) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } // 字典转模型 init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } }
mit
b230406b004c8b5183020b1afdb48c47
19.580645
77
0.52116
3.791976
false
false
false
false
robzimpulse/mynurzSDK
mynurzSDK/Classes/ProfileController.swift
1
4772
// // ProfileController.swift // Pods // // Created by Robyarta on 5/17/17. // // // // Profile.swift // mynurz // // Created by Robyarta on 5/12/17. // Copyright © 2017 kronus. All rights reserved. // import Foundation import RealmSwift public class freelancerProfile: Object { dynamic public var id = 0 dynamic public var firstName = "" dynamic public var lastName = "" dynamic public var email = "" dynamic public var phone = "" dynamic public var roleId = 0 dynamic public var createdAt = 0 dynamic public var updatedAt = 0 dynamic public var uid = "" dynamic public var profession = 0 dynamic public var gender = "" dynamic public var religion = 0 dynamic public var photo = "" dynamic public var idCard = "" dynamic public var countryCode = "" dynamic public var packagePrice = 0 } public class customerProfile: Object { dynamic public var id = 0 dynamic public var firstName = "" dynamic public var lastName = "" dynamic public var email = "" dynamic public var phone = "" dynamic public var roleId = 0 dynamic public var createdAt = 0 dynamic public var updatedAt = 0 dynamic public var uid = "" dynamic public var photo = "" dynamic public var address = "" dynamic public var countryCode = "" dynamic public var stateId = 0 dynamic public var cityId = 0 dynamic public var districtId = 0 dynamic public var areaId = 0 dynamic public var zipCode = "" } public class ProfileController { public static let sharedInstance = ProfileController() private var realm: Realm? public func getFreelancer() -> freelancerProfile? { self.realm = try! Realm() return self.realm!.objects(freelancerProfile.self).first } public func getCustomer() -> customerProfile? { self.realm = try! Realm() return self.realm!.objects(customerProfile.self).first } public func putFreelancer(id: Int, firstName: String, lastName: String, email: String, phone: String, roleId: Int, createdAt: Int, updatedAt: Int, uid: String, profession: Int, gender: String, religion: Int, photo: String, idCard: String, countryCode: String, packagePrice: Int){ self.realm = try! Realm() try! self.realm!.write { let freelancer = freelancerProfile() freelancer.id = id freelancer.firstName = firstName freelancer.lastName = lastName freelancer.email = email freelancer.phone = phone freelancer.roleId = roleId freelancer.createdAt = createdAt freelancer.updatedAt = updatedAt freelancer.uid = uid freelancer.profession = profession freelancer.gender = gender freelancer.religion = religion freelancer.photo = photo freelancer.idCard = idCard freelancer.countryCode = countryCode freelancer.packagePrice = packagePrice if let oldFreelancer = self.realm!.objects(freelancerProfile.self).first { self.realm?.delete(oldFreelancer) } self.realm!.add(freelancer) } } public func putCustomer(id: Int, firstName: String, lastName: String, email: String, phone: String, roleId: Int, createdAt: Int, updatedAt: Int, uid: String, photo: String, address: String, countryCode: String, stateId: Int, cityId: Int, districtId: Int, areaId: Int, zipCode: String){ self.realm = try! Realm() try! self.realm!.write { let customer = customerProfile() customer.id = id customer.firstName = firstName customer.lastName = lastName customer.email = email customer.phone = phone customer.roleId = roleId customer.createdAt = createdAt customer.updatedAt = updatedAt customer.uid = uid customer.photo = photo customer.address = address customer.countryCode = countryCode customer.stateId = stateId customer.cityId = cityId customer.districtId = districtId customer.areaId = areaId customer.zipCode = zipCode if let oldCustomer = self.realm!.objects(customerProfile.self).first { self.realm?.delete(oldCustomer) } self.realm!.add(customer) } } public func drop(){ self.realm = try! Realm() try! self.realm!.write { self.realm?.delete((self.realm?.objects(freelancerProfile.self))!) self.realm?.delete((self.realm?.objects(customerProfile.self))!) } } }
mit
242a99654b513384be4d0859a64de5d4
33.572464
289
0.620834
4.596339
false
false
false
false
StanZabroda/Hydra
Hydra/Collections+Ext.swift
1
846
// // Collections+Ext.swift // Hydra // // Created by Evgeny Evgrafov on 9/23/15. // Copyright © 2015 Evgeny Evgrafov. All rights reserved. // import Foundation extension CollectionType where Index == Int { /// Return a copy of `self` with its elements shuffled func shuffle() -> [Generator.Element] { var list = Array(self) list.shuffleInPlace() return list } } extension MutableCollectionType where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffleInPlace() { // empty and single-element collections don't shuffle if count < 2 { return } for i in 0..<count - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } }
mit
bd1498b23dd8f9c464ca8c71d8baa638
25.4375
66
0.592899
3.930233
false
false
false
false
teads/TeadsSDK-iOS
TeadsSampleApp/Controllers/Native/AppLovin/TableView/NativeAppLovinTableViewController.swift
1
4480
// // NativeAppLovinTableViewController.swift // TeadsSDKIntegrationTestsApp // // Created by Paul Nicolas on 15/02/2022. // import AppLovinSDK import TeadsAppLovinAdapter import TeadsSDK import UIKit class NativeAppLovinTableViewController: TeadsViewController { @IBOutlet var tableView: UITableView! let headerCell = "TeadsContentCell" let teadsAdCellIndentifier = "NativeTableViewCell" let fakeArticleCell = "FakeArticleNativeTableViewCell" let adRowNumber = 3 private var elements = [MANativeAdView?]() private var nativeAdLoader: MANativeAdLoader! private var nativeAdView: MANativeAdView! override func viewDidLoad() { super.viewDidLoad() (0 ..< 8).forEach { _ in elements.append(nil) } ALSdk.shared()?.mediationProvider = ALMediationProviderMAX ALSdk.shared()!.settings.isVerboseLoggingEnabled = true ALSdk.shared()!.initializeSdk { [weak self] (_: ALSdkConfiguration) in self?.loadAd() } } func loadAd() { // FIXME: This ids should be replaced by your own AppLovin AdUnitId let APPLOVIN_AD_UNIT_ID = pid nativeAdLoader = MANativeAdLoader(adUnitIdentifier: APPLOVIN_AD_UNIT_ID) // Setting the modal parent view controller. let teadsAdSettings = TeadsAdapterSettings { settings in settings.enableDebug() settings.pageUrl("https://www.teads.tv") } nativeAdLoader.register(teadsAdSettings: teadsAdSettings) nativeAdLoader.nativeAdDelegate = self nativeAdView = AppLovinNativeAdView.loadNib() nativeAdView.bindViews(with: MANativeAdViewBinder { builder in builder.titleLabelTag = 1 builder.advertiserLabelTag = 2 builder.bodyLabelTag = 3 builder.iconImageViewTag = 4 builder.optionsContentViewTag = 5 builder.mediaContentViewTag = 6 builder.callToActionButtonTag = 7 }) nativeAdLoader.loadAd(into: nativeAdView) } func closeSlot(ad: TeadsAd) { elements.removeAll { $0 == ad } tableView.reloadData() } } extension NativeAppLovinTableViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return elements.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: headerCell, for: indexPath) return cell } else if let nativeAdView = elements[indexPath.row] { guard let cell = tableView.dequeueReusableCell(withIdentifier: teadsAdCellIndentifier, for: indexPath) as? NativeTableViewCell else { return UITableViewCell() } nativeAdView.translatesAutoresizingMaskIntoConstraints = false cell.nativeAdView.addSubview(nativeAdView) nativeAdView.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true nativeAdView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true nativeAdView.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor).isActive = true nativeAdView.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor).isActive = true return cell } else { guard let cell = tableView.dequeueReusableCell(withIdentifier: fakeArticleCell, for: indexPath) as? FakeArticleNativeTableViewCell else { return UITableViewCell() } cell.setMockValues() return cell } } func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return 250 } return 400 } } extension NativeAppLovinTableViewController: MANativeAdDelegate { func didLoadNativeAd(_ nativeAdView: MANativeAdView?, for _: MAAd) { elements.insert(nativeAdView, at: adRowNumber) let indexPaths = [IndexPath(row: adRowNumber, section: 0)] tableView.insertRows(at: indexPaths, with: .automatic) } func didFailToLoadNativeAd(forAdUnitIdentifier _: String, withError _: MAError) { // handle fail to load } func didClickNativeAd(_: MAAd) { print("didClickNativeAd") } }
mit
abff026a1976ab91576018c576dfb039
35.129032
149
0.671652
4.933921
false
false
false
false
redbooth/RealmResultsController
Example/RealmResultsController-iOSTests/RealmLoggerTests.swift
2
10527
// // RealmLoggerTests.swift // RealmResultsController // // Created by Pol Quintana on 6/8/15. // Copyright © 2015 Redbooth. // import Foundation import Quick import Nimble import RealmSwift @testable import RealmResultsController class NotificationListener { static let sharedInstance = NotificationListener() var array: [String : [RealmChange]] = [:] @objc func notificationReceived(_ notification: Foundation.Notification) { array = notification.object as! [String : [RealmChange]] } } class NotificationObserver { var notificationReceived: Bool = false init() { NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "Task-123"), object: nil, queue: nil) { (notification) -> Void in self.notificationReceived = true } } } class RealmLoggerSpec: QuickSpec { override func spec() { var realm: Realm! var logger: RealmLogger! beforeSuite { let configuration = Realm.Configuration(inMemoryIdentifier: "testingRealm") realm = try! Realm(configuration: configuration) logger = RealmLogger(realm: realm) } describe("init(realm:)") { var newLogger: RealmLogger! context("from main thread") { beforeEach { newLogger = RealmLogger(realm: realm) } it("Should have a valid realm and a notificationToken") { expect(newLogger.realm) === realm expect(newLogger.notificationToken).toNot(beNil()) } } context("not from main thread") { var bgRealm: Realm! beforeEach { let queue = DispatchQueue(label: "TESTBG", attributes: []) queue.sync { let configuration = Realm.Configuration(inMemoryIdentifier: "testingRealmBG") bgRealm = try! Realm(configuration: configuration) newLogger = RealmLogger(realm: bgRealm) } } it("Should have a valid realm and a notificationToken") { expect(newLogger.realm) === bgRealm expect(newLogger.notificationToken).toNot(beNil()) } } } describe("finishRealmTransaction()") { let newObject = RealmChange(type: Task.self, action: .add, mirror: nil) let updatedObject = RealmChange(type: Task.self, action: .update, mirror: nil) let deletedObject = RealmChange(type: Task.self, action: .delete, mirror: nil) context("from main thread") { beforeEach { logger.cleanAll() logger.temporary.append(newObject) logger.temporary.append(updatedObject) logger.temporary.append(deletedObject) NotificationCenter.default.addObserver(NotificationListener.sharedInstance, selector: #selector(NotificationListener.notificationReceived), name: NSNotification.Name(rawValue: "realmChangesTest"), object: nil) logger.finishRealmTransaction() } afterEach { NotificationCenter.default.removeObserver(self) } it("Should have received a notification with a valid dictionary") { let notificationArray = NotificationListener.sharedInstance.array var createdObject: Bool = false var updatedObject: Bool = false var deletedObject: Bool = false for object: RealmChange in notificationArray[realm.realmIdentifier]! { if object.action == RealmAction.add { createdObject = true} if object.action == RealmAction.update { updatedObject = true} if object.action == RealmAction.delete { deletedObject = true} } expect(createdObject).to(beTruthy()) expect(updatedObject).to(beTruthy()) expect(deletedObject).to(beTruthy()) } } context("not from main thread") { beforeEach { var newLogger: RealmLogger! let queue = DispatchQueue(label: "TESTBG", attributes: []) queue.sync { let configuration = Realm.Configuration(inMemoryIdentifier: "testingRealmBG") let realm = try! Realm(configuration: configuration) newLogger = RealmLogger(realm: realm) } newLogger.cleanAll() newLogger.temporary.append(newObject) newLogger.temporary.append(updatedObject) newLogger.temporary.append(deletedObject) NotificationCenter.default.addObserver(NotificationListener.sharedInstance, selector: #selector(NotificationListener.notificationReceived), name: NSNotification.Name(rawValue: "realmChangesTest"), object: nil) newLogger.finishRealmTransaction() } afterEach { NotificationCenter.default.removeObserver(self) } it("Should have received a notification with a valid dictionary") { let notificationArray = NotificationListener.sharedInstance.array var createdObject: Bool = false var updatedObject: Bool = false var deletedObject: Bool = false for object: RealmChange in notificationArray[realm.realmIdentifier]! { if object.action == RealmAction.add { createdObject = true} if object.action == RealmAction.update { updatedObject = true} if object.action == RealmAction.delete { deletedObject = true} } expect(createdObject).to(beTruthy()) expect(updatedObject).to(beTruthy()) expect(deletedObject).to(beTruthy()) } } } describe("didAdd<T: Object>(object: T)") { var newObject: Task! beforeEach { newObject = Task() logger.cleanAll() newObject.name = "New Task" logger.didAdd(newObject) } afterEach { logger.cleanAll() } it("Should be added to the temporaryAdded array") { expect(logger.temporary.count).to(equal(1)) expect(logger.temporary.first!.action).to(equal(RealmAction.add)) } } describe("didUpdate<T: Object>(object: T)") { var updatedObject: Task! beforeEach { updatedObject = Task() logger.cleanAll() updatedObject.name = "Updated Task" logger.didUpdate(updatedObject) } afterEach { logger.cleanAll() } it("Should be added to the temporaryAdded array") { expect(logger.temporary.count).to(equal(1)) expect(logger.temporary.first!.action).to(equal(RealmAction.update)) } } describe("didDelete<T: Object>(object: T)") { var deletedObject: Task! beforeEach { deletedObject = Task() logger.cleanAll() deletedObject.name = "Deleted Task" logger.didDelete(deletedObject) } afterEach { logger.cleanAll() } it("Should be added to the temporaryAdded array") { expect(logger.temporary.count).to(equal(1)) expect(logger.temporary.first!.action).to(equal(RealmAction.delete)) } } describe("finishRealmTransaction()") { let observer = NotificationObserver() var newObject: RealmChange! context("object without mirror") { beforeEach { newObject = RealmChange(type: Task.self, action: .add, mirror: nil) logger.cleanAll() logger.temporary.append(newObject) logger.finishRealmTransaction() logger.cleanAll() } it("Should remove all the objects in each temporary array") { expect(logger.temporary.count).to(equal(0)) } it("doesn;t send notification") { expect(observer.notificationReceived).to(beFalsy()) } } context("object with mirror without primaryKey") { beforeEach { newObject = RealmChange(type: Task.self, action: .add, mirror: Dummy()) logger.cleanAll() logger.temporary.append(newObject) logger.finishRealmTransaction() logger.cleanAll() } it("Should remove all the objects in each temporary array") { expect(logger.temporary.count).to(equal(0)) } it("doesn;t send notification") { expect(observer.notificationReceived).to(beFalsy()) } } context("object with mirror and primaryKey") { beforeEach { let task = Task() task.id = 123 newObject = RealmChange(type: Task.self, action: .add, mirror: task) logger.cleanAll() logger.temporary.append(newObject) logger.finishRealmTransaction() logger.cleanAll() } it("Should remove all the objects in each temporary array") { expect(logger.temporary.count).to(equal(0)) } it("doesn;t send notification") { expect(observer.notificationReceived).to(beTruthy()) } } } } }
mit
ff42bb09dfc7c750436060864bc225a0
41.615385
229
0.523751
5.640943
false
false
false
false
wangchong321/tucao
WCWeiBo/WCWeiBo/Classes/Model/OAuth/OAuthViewController.swift
1
3535
// // OAuthViewController.swift // WCWeiBo // // Created by 王充 on 15/5/12. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit import SVProgressHUD class OAuthViewController: UIViewController, UIWebViewDelegate { let WB_Client_Id = "1314580718" let WB_Redirect_Uri = "http://www.tucao.cc" let WB_Client_Secret = "60e4d6ee7f70e32fc42cb967b8957971" @IBAction func close() { dismissViewControllerAnimated(true, completion: nil) SVProgressHUD.dismiss() } override func viewDidLoad() { super.viewDidLoad() // 登陆的时候要将授权页面弹出 let urlString = "https://api.weibo.com/oauth2/authorize?client_id="+WB_Client_Id+"&redirect_uri="+WB_Redirect_Uri let url = NSURL(string: urlString) (view as! UIWebView).loadRequest(NSURLRequest(URL: url!)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* http://m.weibo.cn/reg/index? 点击注册 http://login.sina.com.cn/sso/logout.php? 切换账号 https://api.weibo.com/oauth2/ 点击取消 https://api.weibo.com/oauth2/authorize? 登陆成功 http://www.tucao.cc/?code=018659eb7b1366678882060abda5bb1d code */ // MARK - UIWebView的代理方法 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { // println(request.URL!) // return true // 调用url完整的字符串String类型 //println(request.URL!.absoluteString!) let requestString = request.URL!.absoluteString! if requestString.hasPrefix("https://api.weibo.com/") { return true } if !requestString.hasPrefix(WB_Redirect_Uri) { return false } // 下面要取得code=后面的字符串 if request.URL!.query!.hasPrefix("code=") { // 截取后面的字符串 拿到code //lengthOfBytesUsingEncoding以utf8编码计算字符串长度 let code = (request.URL!.query! as NSString).substringFromIndex("code=".lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) loadAccessToken(code) println("验证码"+code) }else{ println("用户拒绝") close() } return false } // 获取access_token func loadAccessToken(code:String){ let parame = ["client_id":WB_Client_Id, "client_secret":WB_Client_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_Redirect_Uri ] UserAccount.loadAccessToken(parame, comletion: { (account) -> () in if account == nil { // 错误处理 SVProgressHUD.showInfoWithStatus("您的网络不给力") return } sharedUserAccount = account NSNotificationCenter.defaultCenter().postNotificationName(WCSwitchRootViewControllerNotification, object: "Main") self.dismissViewControllerAnimated(true, completion: nil) return }) } func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.show() } func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.dismiss() } }
mit
003bac1b46c528a046c519324e12082b
32.727273
137
0.602875
4.452
false
false
false
false
1457792186/JWSwift
SwiftLearn/SwiftDemo/SwiftDemo/Home/Model/JWHomeDetailModel.swift
1
747
// // JWHomeDetailModel.swift // SwiftDemo // // Created by apple on 17/5/4. // Copyright © 2017年 UgoMedia. All rights reserved. // import UIKit class JWHomeDetailModel: NSObject { @objc var title:String; @objc var imageName:String; @objc var type:String; @objc var audienceCount:Int; @objc var uper:String; @objc init(dataDic:NSDictionary) { title = dataDic.value(forKey:"title") as! String; imageName = dataDic.value(forKey: "imageName") as! String; let persons:String = dataDic.value(forKey: "audienceCount") as! String; audienceCount = Int(persons)!; type = dataDic.value(forKey:"type") as! String; uper = dataDic.value(forKey: "uper") as! String; } }
apache-2.0
83949a8047639d3ed0bdb467eb9e0ca8
27.615385
79
0.646505
3.594203
false
false
false
false
quickthyme/PUTcat
PUTcat/Presentation/TransactionDetail/ViewModel/TransactionDetailViewDataBuilder.swift
1
8130
import UIKit class TransactionDetailViewDataBuilder { struct CellID { static let BasicCell = "BasicCell" static let ValueCell = "ValueCell" static let PickerCell = "PickerCell" static let SwitchCell = "SwitchCell" static let TextViewCell = "TextViewCell" } struct SegueID { static let Header = "SegueID.Header" static let Parameter = "SegueID.Parameter" static let Parser = "SegueID.Parser" static let Send = "SegueID.Send" } struct Icon { static let Transaction = "iconTransaction" } struct EditKey { static let Method = "method" static let Delivery = "delivery" static let BaseURL = "baseURL" static let Parsing = "parsing" static let RelativeURL = "relativeURL" static let RawBody = "rawBody" } static func constructViewData(transaction: PCTransaction) -> TransactionDetailViewData { return TransactionDetailViewData( section: [ TransactionDetailViewDataSection( title: "URL", item: [ // Method TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.PickerCell, title: "Method", detail: transaction.method.rawValue, detailColor: AppColor.Text.TransactionMethod, detailEditKey: EditKey.Method, detailEditOptions: PCTransaction.Methods, segue: nil, icon: nil, accessory: .none ), // Base URL TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.ValueCell, title: "Base", detail: transaction.urlBase ?? "https://", detailColor: AppColor.Text.TransactionURL, detailEditKey: EditKey.BaseURL, detailEditOptions: nil, segue: nil, icon: nil, accessory: .none ), // Relative URL TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.ValueCell, title: "Path", detail: transaction.urlRelative ?? "", detailColor: AppColor.Text.TransactionPath, detailEditKey: EditKey.RelativeURL, detailEditOptions: nil, segue: nil, icon: nil, accessory: .none ), ] ), TransactionDetailViewDataSection( title: "Content", item: [ // Delivery TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.PickerCell, title: "Delivery", detail: transaction.delivery.rawValue, detailColor: AppColor.Text.TransactionDelivery, detailEditKey: EditKey.Delivery, detailEditOptions: ["form", "json"], segue: nil, icon: nil, accessory: .none ), // Headers TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.ValueCell, title: "Headers", detail: "\(transaction.headers?.count ?? 0)", detailColor: AppColor.Text.Light, detailEditKey: nil, detailEditOptions: nil, segue: SegueID.Header, icon: nil, accessory: .disclosureIndicator ), // Parameters | Body (transaction.delivery == .form) ? TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.ValueCell, title: "Parameters", detail: "\(transaction.parameters?.count ?? 0)", detailColor: AppColor.Text.Light, detailEditKey: nil, detailEditOptions: nil, segue: SegueID.Parameter, icon: nil, accessory: .disclosureIndicator ) : TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.TextViewCell, title: "Body", detail: transaction.rawBody, detailColor: AppColor.Text.Light, detailEditKey: EditKey.RawBody, detailEditOptions: nil, segue: nil, icon: nil, accessory: .none ) ] ), TransactionDetailViewDataSection( title: "Result", item: { // Parse let parsingChoice = TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.SwitchCell, title: "Parsing", detail: (transaction.parsing) ? "enabled" : "", detailColor: AppColor.Blue.Dark, detailEditKey: EditKey.Parsing, detailEditOptions: nil, segue: nil, icon: nil, accessory: .none ) if (transaction.parsing) { return [ parsingChoice, TransactionDetailViewDataItem( refID: transaction.id, cellID: CellID.ValueCell, title: "Parsers", detail: "\(transaction.parsers?.count ?? 0)", detailColor: AppColor.Text.Light, detailEditKey: nil, detailEditOptions: nil, segue: SegueID.Parser, icon: nil, accessory: .disclosureIndicator ) ] } else { return [parsingChoice] } }() ) ] ) } }
apache-2.0
82fe0b48d17ae056d9a569f5f1d7eb90
42.244681
92
0.366421
7.534754
false
false
false
false
jtsmrd/Intrview
ViewControllers/ProfileTBC.swift
1
9519
// // profileTBC.swift // SnapInterview // // Created by JT Smrdel on 1/24/17. // Copyright © 2017 SmrdelJT. All rights reserved. // import UIKit class ProfileTBC: UITabBarController, UITabBarControllerDelegate { var profile = (UIApplication.shared.delegate as! AppDelegate).profile var profileTVC: ProfileTVC! var interviewsTVC: InterviewsTVC! var businessSearchVC: BusinessSearchVC! var spotlightsTVC: SpotlightsTVC! var interviewTemplateTVC: InterviewTemplateTVC! var individualSearchVC: IndividualSearchVC! var newInterviewCount: Int! var profileNavController: UINavigationController! var interviewTemplateNavController: UINavigationController! var interviewsNavController: UINavigationController! var individualSearchNavController: UINavigationController! var spotlightNavController: UINavigationController! var businessSearchNavController: UINavigationController! override func viewDidLoad() { super.viewDidLoad() newInterviewCount = 0 tabBar.tintColor = Global.greenColor NotificationCenter.default.addObserver(self, selector: #selector(fetchUpdates), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) profileTVC = ProfileTVC(nibName: "ProfileTVC", bundle: nil) profileTVC.viewType = ViewType.Edit let profileTabBarItem = UITabBarItem(title: "Profile", image: UIImage(named: "profile_icon"), selectedImage: UIImage(named: "profile_icon")) profileTVC.tabBarItem = profileTabBarItem profileNavController = UINavigationController() profileNavController.navigationBar.isTranslucent = false profileNavController.viewControllers = [profileTVC] interviewTemplateTVC = InterviewTemplateTVC(nibName: "InterviewTemplateTVC", bundle: nil) let interviewTemplateTabBarItem = UITabBarItem(title: "InterviewTypes", image: UIImage(named: "template_icon"), selectedImage: UIImage(named: "template_icon")) interviewTemplateTVC.tabBarItem = interviewTemplateTabBarItem interviewTemplateNavController = UINavigationController() interviewTemplateNavController.navigationBar.isTranslucent = false interviewTemplateNavController.viewControllers = [interviewTemplateTVC] interviewsTVC = InterviewsTVC(nibName: "InterviewsTVC", bundle: nil) let interviewsTabBarItem = UITabBarItem(title: "Interviews", image: UIImage(named: "interview_icon"), selectedImage: UIImage(named: "interview_icon")) interviewsTVC.tabBarItem = interviewsTabBarItem interviewsNavController = UINavigationController() interviewsNavController.navigationBar.isTranslucent = false interviewsNavController.viewControllers = [interviewsTVC] individualSearchVC = IndividualSearchVC(nibName: "IndividualSearchVC", bundle: nil) let individualSearchTabBarItem = UITabBarItem(title: "Search", image: UIImage(named: "search_icon"), selectedImage: UIImage(named: "search_icon")) individualSearchVC.tabBarItem = individualSearchTabBarItem individualSearchNavController = UINavigationController() individualSearchNavController.navigationBar.isTranslucent = false individualSearchNavController.viewControllers = [individualSearchVC] spotlightsTVC = SpotlightsTVC(nibName: "SpotlightsTVC", bundle: nil) let spotlightTabBarItem = UITabBarItem(title: "Spotlight", image: UIImage(named: "spotlight_icon"), selectedImage: UIImage(named: "spotlight_icon")) spotlightsTVC.tabBarItem = spotlightTabBarItem spotlightNavController = UINavigationController() spotlightNavController.navigationBar.isTranslucent = false spotlightNavController.viewControllers = [spotlightsTVC] businessSearchVC = BusinessSearchVC(nibName: "BusinessSearchVC", bundle: nil) let businessSearchTabBarItem = UITabBarItem(title: "Search", image: UIImage(named: "search_icon"), selectedImage: UIImage(named: "search_icon")) businessSearchVC.tabBarItem = businessSearchTabBarItem businessSearchNavController = UINavigationController() businessSearchNavController.navigationBar.isTranslucent = false businessSearchNavController.viewControllers = [businessSearchVC] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switch profile.profileType! { case .Business: viewControllers = [interviewsNavController, interviewTemplateNavController, individualSearchNavController, spotlightNavController, profileNavController] case .Individual: viewControllers = [interviewsNavController, businessSearchNavController, spotlightNavController, profileNavController] } if !profile.exists { // Set to profile tab self.selectedViewController = profileNavController } } @objc func fetchUpdates() { if profile.exists { switch profile.profileType! { case .Business: profile.businessProfile?.interviewCollection.fetchAllInterviews(with: profile.cKRecordName!, profileType: .Business, completion: { let newInterviewCount = self.profile.businessProfile?.interviewCollection.interviews.filter({ (interview) -> Bool in interview.businessNewFlag == true }).count if let count = newInterviewCount { if count > 0 { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = "\(count)" self.interviewsTVC.sortAndRefreshInterviews() } } else { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = nil } } } }) profile.businessProfile?.spotlightCollection.fetchAllSpotlights(with: profile.cKRecordName!, profileType: .Business, completion: { let newSpotlightCount = self.profile.businessProfile?.spotlightCollection.spotlights.filter({ (spotlight) -> Bool in spotlight.businessNewFlag == true }).count if let count = newSpotlightCount { if count > 0 { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = "\(count)" } } else { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = nil } } } }) case .Individual: profile.individualProfile?.interviewCollection.fetchAllInterviews(with: profile.cKRecordName!, profileType: .Individual, completion: { let newInterviewCount = self.profile.individualProfile?.interviewCollection.interviews.filter({ (interview) -> Bool in interview.individualNewFlag == true }).count if let count = newInterviewCount { if count > 0 { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = "\(count)" self.interviewsTVC.sortAndRefreshInterviews() } } else { DispatchQueue.main.async { self.interviewsTVC.tabBarItem.badgeValue = nil } } } }) profile.individualProfile?.spotlightCollection.fetchAllSpotlights(with: profile.cKRecordName!, profileType: .Individual, completion: { let newSpotlightCount = self.profile.individualProfile?.spotlightCollection.spotlights.filter({ (spotlight) -> Bool in spotlight.individualNewFlag == true }).count if let count = newSpotlightCount { if count > 0 { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = "\(count)" } } else { DispatchQueue.main.async { self.spotlightsTVC.tabBarItem.badgeValue = nil } } } }) } } } }
mit
76397d7b9888c51281284a265fbead0d
45.429268
167
0.579849
6.184535
false
false
false
false
HotCocoaTouch/DeclarativeLayout
DeclarativeLayout/Classes/ViewLayout.swift
1
7127
import UIKit public final class ViewLayout<T: UIView> { private unowned var view: T private var currentLayoutComponent: UIViewLayoutComponent<T> private var currentConstraints: [LayoutConstraint]? private let cachedLayoutObjectStore = CachedLayoutObjectStore() /** Initialize your view layout with the root view you are defining a layout for - parameters: - view: The root view you would like to define a layout for */ public init(view: T) { self.view = view currentLayoutComponent = UIViewLayoutComponent(view: view, cachedLayoutObjectStore: cachedLayoutObjectStore) } /** Update your layout - parameters: - layoutClosure: A closure that will define the layout component for the ViewLayout's view */ public func updateLayoutTo(_ layoutClosure: (UIViewLayoutComponent<T>) -> ()) { let layoutComponent = UIViewLayoutComponent(view: view, cachedLayoutObjectStore: cachedLayoutObjectStore) layoutClosure(layoutComponent) removeUnneededArrangedSubviews(with: layoutComponent) removeUnneededLayougGuides(with: layoutComponent) addSubviewsAndLayoutGuides(with: layoutComponent) removeUnneededSubviews(with: layoutComponent) updateConstraints(with: layoutComponent) currentLayoutComponent = layoutComponent } private func addSubviewsAndLayoutGuides(with layoutComponent: UIViewLayoutComponentType) { for (i, subview) in layoutComponent.subviews.enumerated() { layoutComponent.downcastedView.insertSubview(subview, at: i) } for layoutGuide in layoutComponent.layoutGuides { layoutComponent.downcastedView.addLayoutGuide(layoutGuide) } addSubviewsAndLayoutGuidesForSublayoutComponents(with: layoutComponent) } private func addSubviewsAndLayoutGuides(with layoutComponent: UIStackViewLayoutComponentType) { for (i, subview) in layoutComponent.subviews.enumerated() { layoutComponent.downcastedView.insertSubview(subview, at: i) } for layoutGuide in layoutComponent.layoutGuides { layoutComponent.downcastedView.addLayoutGuide(layoutGuide) } addSubviewsAndLayoutGuidesForSublayoutComponents(with: layoutComponent) } private func addSubviewsAndLayoutGuidesForSublayoutComponents(with layoutComponent: ViewLayoutComponentType) { for sublayoutComponent in layoutComponent.sublayoutComponents { switch sublayoutComponent { case .uiview(let layoutComponent): addSubviewsAndLayoutGuides(with: layoutComponent) case .uistackview(let layoutComponent): addSubviewsAndLayoutGuides(with: layoutComponent) for (i, subview) in layoutComponent.arrangedSubviews.enumerated() { layoutComponent.downcastedView.insertArrangedSubview(subview, at: i) } if #available(iOS 11.0, *) { for customSpacing in layoutComponent.customSpacings { layoutComponent.downcastedView.setCustomSpacing(customSpacing.space, after: customSpacing.afterView) } } case .layoutGuide: break } } } private func removeUnneededSubviews(with layoutComponent: UIViewLayoutComponent<T>) { let layoutComponentSubviews = Set(layoutComponent.allSubviews()) currentLayoutComponent.allSubviews() .filter { !layoutComponentSubviews.contains($0) } .forEach { $0.removeFromSuperview() } } private func removeUnneededArrangedSubviews(with layoutComponent: ViewLayoutComponentType) { let currentArrangedSubviews = currentLayoutComponent.allArrangedSubviews() let newArrangedSubviews = layoutComponent.allArrangedSubviews() for (view, currentLayoutComponent) in currentArrangedSubviews { if newArrangedSubviews[view] == nil { view.removeFromSuperview() } else if let newComponent = newArrangedSubviews[view], newComponent.downcastedView != currentLayoutComponent.downcastedView { view.removeFromSuperview() } } } private func removeUnneededLayougGuides(with layoutComponent: UIViewLayoutComponent<T>) { let currentLayoutGuides = currentLayoutComponent.allLayoutGuides() let newLayoutGuides = layoutComponent.allLayoutGuides() for (layoutGuide, owningView) in currentLayoutGuides { if newLayoutGuides[layoutGuide] == nil { owningView.removeLayoutGuide(layoutGuide) } else if let newOwningView = newLayoutGuides[layoutGuide], newOwningView != owningView { owningView.removeLayoutGuide(layoutGuide) } } } private func updateConstraints(with layoutComponent: UIViewLayoutComponent<T>) { let newConstraintsArray = layoutComponent.allConstraints() let currentConstraintsArray = currentConstraints ?? [] if currentConstraintsArray.isEmpty { NSLayoutConstraint.activate(newConstraintsArray.map { $0.wrappedConstraint }) currentConstraints = newConstraintsArray } else { let newConstraints = Set(newConstraintsArray) var currentConstraints = Set(currentConstraintsArray) let matchingConstraints = newConstraints.intersection(currentConstraints) let constraintsToRemove = currentConstraints.subtracting(matchingConstraints) let constraintsToAdd = newConstraints.subtracting(matchingConstraints) var updatedCurrentConstraints = constraintsToAdd.map { $0 } for constraint in matchingConstraints { let matchingConstraint = currentConstraints.remove(constraint)! updatedCurrentConstraints.append(matchingConstraint) let matchingWrappedConstraint = matchingConstraint.wrappedConstraint let wrappedConstraint = constraint.wrappedConstraint if matchingWrappedConstraint.constant != wrappedConstraint.constant { matchingWrappedConstraint.constant = wrappedConstraint.constant } if matchingWrappedConstraint.priority != wrappedConstraint.priority { matchingWrappedConstraint.priority = wrappedConstraint.priority } if matchingWrappedConstraint.identifier != wrappedConstraint.identifier { matchingWrappedConstraint.identifier = wrappedConstraint.identifier } } NSLayoutConstraint.deactivate(constraintsToRemove.map { $0.wrappedConstraint }) NSLayoutConstraint.activate(constraintsToAdd.map { $0.wrappedConstraint }) self.currentConstraints = updatedCurrentConstraints } } }
mit
714f4c4df7bc8ecd14757acfe1d1115e
42.993827
124
0.674337
5.77085
false
false
false
false
lorentey/swift
test/IRGen/address_sanitizer_recover.swift
5
789
// RUN: %target-swift-frontend -emit-ir -sanitize=address -sanitize-recover=address %s | %FileCheck %s -check-prefix=ASAN_RECOVER // RUN: %target-swift-frontend -emit-ir -sanitize=address %s | %FileCheck %s -check-prefix=ASAN_NO_RECOVER // RUN: %target-swift-frontend -emit-ir -sanitize-recover=address %s | %FileCheck %s -check-prefix=NO_ASAN_RECOVER // ASAN_RECOVER: declare void @__asan_loadN_noabort( // ASAN_NO_RECOVER: declare void @__asan_loadN( let size:Int = 128; let x = UnsafeMutablePointer<UInt8>.allocate(capacity: size) x.initialize(repeating: 0, count: size) x.advanced(by: 0).pointee = 5; print("Read first element:\(x.advanced(by: 0).pointee)") x.deallocate(); // There should be no ASan instrumentation in this case. // NO_ASAN_RECOVER-NOT: declare void @__asan_load
apache-2.0
689f95ddf03a5cb8900a7455ed92c408
48.3125
129
0.727503
3.181452
false
false
false
false
hooman/swift
stdlib/public/Concurrency/AsyncPrefixSequence.swift
3
3781
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 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 // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.5, *) extension AsyncSequence { /// Returns an asynchronous sequence, up to the specified maximum length, /// containing the initial elements of the base asynchronous sequence. /// /// Use `prefix(_:)` to reduce the number of elements produced by the /// asynchronous sequence. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `prefix(_:)` method causes the modified /// sequence to pass through the first six values, then end. /// /// for await number in Counter(howHigh: 10).prefix(6) { /// print("\(number) ") /// } /// // prints "1 2 3 4 5 6" /// /// If the count passed to `prefix(_:)` exceeds the number of elements in the /// base sequence, the result contains all of the elements in the sequence. /// /// - Parameter count: The maximum number of elements to return. The value of /// `count` must be greater than or equal to zero. /// - Returns: An asynchronous sequence starting at the beginning of the /// base sequence with at most `count` elements. @inlinable public __consuming func prefix( _ count: Int ) -> AsyncPrefixSequence<Self> { precondition(count >= 0, "Can't prefix a negative number of elements from an async sequence") return AsyncPrefixSequence(self, count: count) } } /// An asynchronous sequence, up to a specified maximum length, /// containing the initial elements of a base asynchronous sequence. @available(SwiftStdlib 5.5, *) @frozen public struct AsyncPrefixSequence<Base: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let count: Int @inlinable init(_ base: Base, count: Int) { self.base = base self.count = count } } @available(SwiftStdlib 5.5, *) extension AsyncPrefixSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The prefix sequence produces whatever type of element its base iterator /// produces. public typealias Element = Base.Element /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the prefix sequence. @frozen public struct Iterator: AsyncIteratorProtocol { @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline var remaining: Int @inlinable init(_ baseIterator: Base.AsyncIterator, count: Int) { self.baseIterator = baseIterator self.remaining = count } /// Produces the next element in the prefix sequence. /// /// Until reaching the number of elements to include, this iterator calls /// `next()` on its base iterator and passes through the result. After /// reaching the maximum number of elements, subsequent calls to `next()` /// return `nil`. @inlinable public mutating func next() async rethrows -> Base.Element? { if remaining != 0 { remaining &-= 1 return try await baseIterator.next() } else { return nil } } } @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), count: count) } }
apache-2.0
b513f2a4a7de72abe69fbf25c8ed8844
32.460177
80
0.656176
4.714464
false
false
false
false
soheil/SwiftCSS
Example/SwiftCSS/ViewController.swift
1
3055
// // ViewController.swift // SwiftCSS // // Created by Soheil on 03/07/2016. // Copyright (c) 2016 Soheil. All rights reserved. // import UIKit class ViewController: UIViewController { var pic = UIImageView() var name = UILabel() var addBtn = UIButton() var plusBtn = UIButton() var minusBtn = UIButton() var count = UILabel() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() let bundlePath = NSBundle.mainBundle().pathForResource("flower", ofType: "png") let image = UIImage(contentsOfFile: bundlePath!) pic = UIImageView(image: image) view.addSubview(pic) name.text = "I make your like easy." name.textColor = UIColor.blackColor() name.textAlignment = NSTextAlignment.Center view.addSubview(name) addBtn.setTitle(" Add to Cart", forState: UIControlState.Normal) addBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) addBtn.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside) addBtn.backgroundColor = UIColor.grayColor() addBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(20) view.addSubview(addBtn) minusBtn = UIButton(frame: CGRectMake(10, 0, 30, 30)) minusBtn.setTitle("–", forState: UIControlState.Normal) minusBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) minusBtn.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside) minusBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(22) view.addSubview(minusBtn) count = UILabel(frame: CGRectMake(0, 0, 30, 30)) count.text = "1" count.textColor = UIColor.whiteColor() count.backgroundColor = UIColor.lightGrayColor() count.font = UIFont.boldSystemFontOfSize(20) count.textAlignment = NSTextAlignment.Center view.addSubview(count) plusBtn = UIButton(frame: CGRectMake(0, 0, 30, 30)) plusBtn.setTitle("+", forState: UIControlState.Normal) plusBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) plusBtn.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside) plusBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(22) view.addSubview(plusBtn) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() pic.marginTop = 100 pic.height = 150 pic.widthPercent = 50 name.marginTop = 20 name.widthPercent = 80 name.height = 50 addBtn.widthPercent = 100 addBtn.height = 50 addBtn.marginBottomAbsolute = 0 minusBtn.marginBottomAbsolute = 10 plusBtn.marginBottomAbsolute = 10 plusBtn.marginLeft = 10 count.marginBottomAbsolute = 10 count.marginLeft = 10 } }
mit
88e03ac8617d1d1e91f28c58e68bdb39
34.5
94
0.64756
4.853736
false
false
false
false
dnevera/IMProcessing
IMProcessing/Classes/Graphics/IMPTransformFilter.swift
1
6633
// // IMPTransformFilter.swift // IMProcessing // // Created by denis svinarchuk on 20.04.16. // Copyright © 2016 ImageMetalling. All rights reserved. // import Metal /// Transform filter can be imagine as a photo plate tool typealias IMPPhotoPlateFilter = IMPTransformFilter /// Image textured on the model of Rendering Node is a Cube Node with virtual depth == 0 public class IMPPhotoPlateNode: IMPRenderNode { /// Cropping the plate region public var region = IMPRegion() { didSet{ if region.left != oldValue.left || region.right != oldValue.right || region.top != oldValue.top || region.bottom != oldValue.bottom { vertices = IMPPhotoPlate(aspect: aspect, region: region) } } } var resetAspect:Bool = true override public var aspect:Float { didSet{ if super.aspect != oldValue || resetAspect { super.aspect = aspect resetAspect = false vertices = IMPPhotoPlate(aspect: aspect, region: self.region) } } } public init(context: IMPContext, aspectRatio:Float, region:IMPRegion = IMPRegion()){ super.init(context: context, vertices: IMPPhotoPlate(aspect: aspectRatio, region: self.region)) } } /// Photo plate transformation filter public class IMPTransformFilter: IMPFilter, IMPGraphicsProvider { public var backgroundColor:IMPColor = IMPColor.whiteColor() public override var source: IMPImageProvider? { didSet { updatePlateAspect(region) } } public var keepAspectRatio = true public var graphics:IMPGraphics! required public init(context: IMPContext, vertex:String, fragment:String) { super.init(context: context) graphics = IMPGraphics(context: context, vertex: vertex, fragment: fragment) } convenience public required init(context: IMPContext) { self.init(context: context, vertex: "vertex_transformation", fragment: "fragment_transformation") } public var viewPortSize: MTLSize? { didSet{ plate.aspect = self.keepAspectRatio ? viewPortSize!.width.float/viewPortSize!.height.float : 1 dirty = true } } public override func main(source source:IMPImageProvider , destination provider: IMPImageProvider) -> IMPImageProvider? { self.context.execute{ (commandBuffer) -> Void in if let inputTexture = source.texture { var width = inputTexture.width.float var height = inputTexture.height.float if let s = self.viewPortSize { width = s.width.float height = s.height.float } width -= width * (self.plate.region.left + self.plate.region.right); height -= height * (self.plate.region.bottom + self.plate.region.top); if width.int != provider.texture?.width || height.int != provider.texture?.height{ let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( inputTexture.pixelFormat, width: width.int, height: height.int, mipmapped: false) provider.texture = self.context.device.newTextureWithDescriptor(descriptor) } self.plate.render(commandBuffer, pipelineState: self.graphics.pipeline!, source: source, destination: provider, clearColor: self.clearColor, configure: { (command) in self.configureGraphics(self.graphics, command: command) }) } } return provider } public var aspect:Float { return plate.aspect } public var model:IMPTransfromModel { return plate.model } public var identityModel:IMPTransfromModel { return plate.identityModel } public func configureGraphics(graphics:IMPGraphics, command:MTLRenderCommandEncoder){} /// Rotate plate on angle in radians arround axis /// /// - parameter vector: angle in radians for x,y,z axis public var angle:float3 { set { plate.angle = newValue dirty = true } get { return plate.angle } } /// Scale plate /// /// - parameter vector: x,y,z scale factor public var scale:float3 { set { plate.scale = newValue dirty = true } get { return plate.scale } } /// Scale plate with global 2D factor /// /// - parameter factor: public func scale(factor f:Float){ plate.scale = float3(f,f,1) dirty = true } /// Move plate with vector /// /// - parameter vector: vector public var translation: float2 { set{ plate.translation = newValue dirty = true } get { return plate.translation } } /// Cut the plate with crop region /// /// - parameter region: crop region public var region:IMPRegion { set { guard (source != nil) else {return} updatePlateAspect(newValue) plate.region = newValue dirty = true } get { return plate.region } } /// Set/get reflection public var reflection:(horizontal:IMPRenderNode.ReflectMode, vertical:IMPRenderNode.ReflectMode) { set{ plate.reflectMode = newValue dirty = true } get{ return plate.reflectMode } } lazy var plate:PhotoPlate = { return PhotoPlate(context: self.context, aspectRatio:4/3) }() func updatePlateAspect(region:IMPRegion) { if let s = source { let width = s.width - s.width * (region.left + region.right); let height = s.height - s.height * (region.bottom + region.top); plate.aspect = self.keepAspectRatio ? width/height : 1 } } // Plate is a cube with virtual depth == 0 class PhotoPlate: IMPPhotoPlateNode {} }
mit
41c0b6f29ef9c7aefa3b76ce125b32b2
29.145455
125
0.551116
4.923534
false
false
false
false
OpenMindBR/swift-diversidade-app
Diversidade/DiscoveringViewController.swift
1
3578
// // DiscoveringViewController.swift // Diversidade // // Created by Francisco José A. C. Souza on 24/02/16. // Copyright © 2016 Francisco José A. C. Souza. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class DiscoveringViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var postsTableView: UITableView! @IBOutlet weak var menuItem: UIBarButtonItem! @IBOutlet weak var loadingPostsIndicator: UIActivityIndicatorView! var datasource:[Post]? override func viewDidLoad() { datasource = [] super.viewDidLoad() self.configureSideMenu(self.menuItem) self.retrieveDiscoveringPosts() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rows = 0 if let datasource = self.datasource { rows = datasource.count } return rows } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("discovering_cell", forIndexPath: indexPath) as! PostTableViewCell if let datasource = self.datasource { let content = datasource[indexPath.row] cell.titleLabel.text = content.title cell.postTextLabel.text = content.text } return cell } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 500.0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if let datasource = datasource, let sourceUrl = datasource[indexPath.row].url { if let url = NSURL(string: sourceUrl) { UIApplication.sharedApplication().openURL(url) } } } func retrieveDiscoveringPosts() { let requestString = UrlFormatter.urlForNewsFromCategory(Category.Discovering) Alamofire.request(.GET, requestString).validate().responseJSON { (response) in switch response.result { case .Success: if let value = response.result.value { let json: Array<JSON> = JSON(value).arrayValue let posts: [Post] = json.map({ (post) -> Post in let text = post["text"].stringValue let title = post["title"].stringValue let url = post["source"].stringValue return Post(title: title, url: url, text: text) }) self.datasource = posts self.loadingPostsIndicator.stopAnimating() self.postsTableView.reloadData() } case .Failure: print (response.result.error) } } } }
mit
9743c06fe0805cecb0c93964c3cb9046
31.798165
129
0.587133
5.851064
false
false
false
false
noprom/swiftmi-app
swiftmi/swiftmi/CodeDal.swift
2
3663
// // CodeDal.swift // swiftmi // // Created by yangyin on 15/4/30. // Copyright (c) 2015年 swiftmi. All rights reserved. // import Foundation import CoreData import SwiftyJSON class CodeDal: NSObject { func addList(items:JSON) { for po in items { self.addCode(po.1, save: false) } CoreDataManager.shared.save() } func addCode(obj:JSON,save:Bool){ let context=CoreDataManager.shared.managedObjectContext; let model = NSEntityDescription.entityForName("Codedown", inManagedObjectContext: context) let codeDown = ShareCode(entity: model!, insertIntoManagedObjectContext: context) if model != nil { self.obj2ManagedObject(obj, codeDown: codeDown) if(save) { CoreDataManager.shared.save() } } } func deleteAll(){ CoreDataManager.shared.deleteTable("Codedown") } func save(){ let context=CoreDataManager.shared.managedObjectContext; do { try context.save() } catch _ { } } func getCodeList()->[AnyObject]? { let request = NSFetchRequest(entityName: "Codedown") let sort1=NSSortDescriptor(key: "createTime", ascending: false) // var sort2=NSSortDescriptor(key: "postId", ascending: false) request.fetchLimit = 30 request.sortDescriptors = [sort1] request.resultType = NSFetchRequestResultType.DictionaryResultType let result = CoreDataManager.shared.executeFetchRequest(request) return result } func obj2ManagedObject(obj:JSON,codeDown:ShareCode) -> ShareCode{ var data = obj codeDown.author = data["author"].string codeDown.categoryId = data["categoryId"].int64Value codeDown.categoryName = data["categoryName"].string codeDown.codeId = data["codeId"].int64Value codeDown.commentCount = data["commentCount"].int32Value codeDown.content = data["content"].string codeDown.contentLength = data["contentLength"].doubleValue codeDown.createTime = data["createTime"].int64Value codeDown.desc = data["desc"].string codeDown.devices = data["devices"].string codeDown.downCount = data["downCount"].int32Value codeDown.downUrl = data["downUrl"].stringValue codeDown.isHtml = data["isHtml"].int32Value codeDown.keywords = data["keywords"].string if data["lastCommentId"].int64 != nil { codeDown.lastCommentId = data["lastCommentId"].int64Value } codeDown.lastCommentTime = data["lastCommentTime"].int64Value codeDown.licence = data["licence"].string codeDown.platform = data["platform"].string codeDown.preview = data["preview"].stringValue codeDown.sourceName = data["sourceName"].stringValue codeDown.sourceType = data["sourceType"].int32Value codeDown.sourceUrl = data["sourceUrl"].stringValue codeDown.state = data["state"].int32Value codeDown.tags = data["tags"].string codeDown.title = data["title"].string codeDown.updateTime = data["updateTime"].int64Value codeDown.userId = data["userId"].int64Value codeDown.username = data["username"].stringValue codeDown.viewCount = data["viewCount"].int32Value return codeDown } }
mit
52c84b57dfcc1f29561bbc6a75dcb3b4
30.025424
98
0.600109
4.868351
false
false
false
false
FearfulFox/sacred-tiles
Sacred Tiles/AboutMenuView.swift
1
2940
// // AboutMenuView.swift // Sacred Tiles // // Created by Fox on 2/25/15. // Copyright (c) 2015 eCrow. All rights reserved. // import UIKit; import SpriteKit; class AboutMenuView: CommonSKView { // /*============================================================ // Main Menu Scene class MyScene: CommonSKScene { // Background Image let backgroundSprite = CommonSKSpriteNode(imageNamed: "AboutMenuOne", size: CGSize(width: 1.0, height: 1.0)); // Header labels let regularTileLabel = CommonSKLabelNode(text: "Regular Tiles", type: CommonSKLabelNode.TYPE.Header1); let hueRingTileLabel = CommonSKLabelNode(text: "Hue Ring Tile", type: CommonSKLabelNode.TYPE.Header1); let bombTileLabel = CommonSKLabelNode(text: "Bomb Tile", type: CommonSKLabelNode.TYPE.Header1); // Buttons let mainMenuButton = ButtonSprite(text: "Main Menu", type: ButtonSprite.TYPE.Small); override init(){ super.init(); } override func didMoveToView(view: SKView) { self.backgroundColor = SKColor(red: 0.62, green: 0.52, blue: 0.36, alpha: 1.0); self.initObjects(); self.initClosures(); // Background self.addChild(self.backgroundSprite); // Labels self.addChild(self.regularTileLabel); self.addChild(self.hueRingTileLabel); self.addChild(self.bombTileLabel); // Buttons self.addChild(self.mainMenuButton); } private func initObjects(){ // The background image self.backgroundSprite.anchorPoint = CGPoint(x: 0.0, y: 0.0); self.backgroundSprite.setPosition(x: 0.0, y: 0.0); // Header labels self.regularTileLabel.setPosition(x: 0.16, y: 0.53); self.hueRingTileLabel.setPosition(x: 0.5, y: 0.53); self.bombTileLabel.setPosition(x: 0.84, y: 0.53); // Buttons self.mainMenuButton.setPosition(x: 0.5, y: 0.04); self.mainMenuButton.setSize(width: 0.167, height: 0.105); } private func initClosures(){ self.mainMenuButton.onClick({(selfNode: SKNode)->() in NAV_CONTROLLER.popToRootWithFade(); }); } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); } }; var myScene: SKScene! = MyScene(); // View Constructor override init(){ super.init(); // Display Debug //self.showDebug(); self.presentScene(self.myScene); } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
176f58087b39b6f27ba4c01f6b11c934
30.612903
117
0.546939
4.441088
false
false
false
false
alecgorge/AGAudioPlayer
Pods/NapySlider/NapySlider/NapySlider.swift
1
13585
// // NapySlider.swift // NapySlider // // Created by Jonas Schoch on 12.12.15. // Copyright © 2015 naptics. All rights reserved. // import UIKit @IBDesignable open class NapySlider: UIControl { // internal variables, our views internal var backgroundView: UIView! internal var titleBackgroundView: UIView! internal var sliderView: UIView! internal var sliderBackgroundView: UIView! internal var sliderFillView: UIView! internal var handleView: UIView! internal var currentPosTriangle: TriangleView! internal var titleLabel: UILabel! internal var handleLabel: UILabel! internal var currentPosLabel: UILabel! internal var maxLabel: UILabel! internal var minLabel: UILabel! internal var isFloatingPoint: Bool { get { return step.truncatingRemainder(dividingBy: 1) != 0 ? true : false } } // public variables var titleHeight: CGFloat = 30 var sliderWidth: CGFloat = 20 var handleHeight: CGFloat = 20 var handleWidth: CGFloat = 50 // public inspectable variables @IBInspectable var title: String = "Hello" { didSet { titleLabel.text = title } } @IBInspectable var min: Double = 0 { didSet { minLabel.text = textForPosition(min) } } @IBInspectable var max: Double = 10 { didSet { maxLabel.text = textForPosition(max) } } @IBInspectable var step: Double = 1 // colors @IBInspectable var handleColor: UIColor = UIColor.gray @IBInspectable var mainBackgroundColor: UIColor = UIColor.groupTableViewBackground @IBInspectable var titleBackgroundColor: UIColor = UIColor.lightGray @IBInspectable var sliderUnselectedColor: UIColor = UIColor.lightGray /** the position of the handle. The handle moves animated when setting the variable */ var handlePosition:Double { set (newHandlePosition) { moveHandleToPosition(newHandlePosition, animated: true) } get { let currentY = handleView.frame.origin.y + handleHeight/2 let positionFromMin = -(Double(currentY) - minPosition - stepheight/2) / stepheight // add an offset if slider should go to a negative value var stepOffset:Double = 0 if min < 0 { let zeroPosition = (0 - min)/Double(step) + 0.5 if positionFromMin < zeroPosition { stepOffset = 0 - step } } // let position = Int((positionFromMin * step + min + stepOffset) / step) * Int(step) let position = Double(Int((positionFromMin * step + min + stepOffset) / step)) * step return Double(position) } } var disabled:Bool = false { didSet { sliderBackgroundView.alpha = disabled ? 0.4 : 1.0 self.isUserInteractionEnabled = !disabled } } fileprivate var steps: Int { get { if (min == max || step == 0) { return 1 } else { return Int(round((max - min) / step)) + 1 } } } fileprivate var maxPosition:Double { get { return 0 } } fileprivate var minPosition:Double { get { return Double(sliderView.frame.height) } } fileprivate var stepheight:Double { get { return (minPosition - maxPosition) / Double(steps - 1) } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override init(frame: CGRect) { super.init(frame: frame) self.setup() } fileprivate func setup() { backgroundView = UIView() backgroundView.isUserInteractionEnabled = false addSubview(backgroundView) titleBackgroundView = UIView() addSubview(titleBackgroundView) titleLabel = UILabel() titleBackgroundView.addSubview(titleLabel) sliderBackgroundView = UIView() sliderBackgroundView.isUserInteractionEnabled = false backgroundView.addSubview(sliderBackgroundView) sliderFillView = UIView() sliderFillView.isUserInteractionEnabled = false sliderBackgroundView.addSubview(sliderFillView) sliderView = UIView() sliderView.isUserInteractionEnabled = false sliderBackgroundView.addSubview(sliderView) handleView = UIView() handleView.isUserInteractionEnabled = false sliderView.addSubview(handleView) handleLabel = UILabel() handleView.addSubview(handleLabel) minLabel = UILabel() backgroundView.addSubview(minLabel) maxLabel = UILabel() backgroundView.addSubview(maxLabel) currentPosLabel = UILabel() sliderBackgroundView.addSubview(currentPosLabel) currentPosTriangle = TriangleView() currentPosLabel.addSubview(currentPosTriangle) } open override func layoutSubviews() { super.layoutSubviews() let sliderPaddingTop:CGFloat = 25 let sliderPaddingBottom:CGFloat = 20 backgroundView.frame = CGRect(x: 0, y: titleHeight, width: frame.size.width, height: frame.size.height - titleHeight) backgroundView.backgroundColor = mainBackgroundColor titleBackgroundView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: titleHeight) titleBackgroundView.backgroundColor = titleBackgroundColor titleLabel.frame = CGRect(x: 0, y: 0, width: titleBackgroundView.frame.width, height: titleBackgroundView.frame.height) titleLabel.text = title titleLabel.textColor = handleColor titleLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightSemibold) titleLabel.textAlignment = NSTextAlignment.center sliderBackgroundView.frame = CGRect(x: backgroundView.frame.width/2 - sliderWidth/2, y: sliderPaddingTop, width: sliderWidth, height: backgroundView.frame.height - (sliderPaddingTop + sliderPaddingBottom)) sliderBackgroundView.backgroundColor = sliderUnselectedColor sliderView.frame = CGRect(x: 0, y: sliderWidth/2, width: sliderBackgroundView.frame.width, height: sliderBackgroundView.frame.height - sliderWidth) sliderView.backgroundColor = UIColor.clear handleView.frame = CGRect(x: -(handleWidth-sliderWidth)/2, y: sliderView.frame.height/2 - handleHeight/2, width: handleWidth, height: handleHeight) handleView.backgroundColor = handleColor sliderFillView.frame = CGRect(x: 0, y: handleView.frame.origin.y + handleHeight, width: sliderBackgroundView.frame.width, height: sliderBackgroundView.frame.height-handleView.frame.origin.y - handleHeight) sliderFillView.backgroundColor = tintColor handleLabel.frame = CGRect(x: 0, y: 0, width: handleWidth, height: handleHeight) handleLabel.text = "" handleLabel.textAlignment = NSTextAlignment.center handleLabel.textColor = UIColor.white handleLabel.font = UIFont.systemFont(ofSize: 11, weight: UIFontWeightBold) handleLabel.backgroundColor = UIColor.clear minLabel.frame = CGRect(x: 0, y: backgroundView.frame.height-20, width: backgroundView.frame.width, height: 20) minLabel.text = textForPosition(min) minLabel.textAlignment = NSTextAlignment.center minLabel.font = UIFont.systemFont(ofSize: 11, weight: UIFontWeightRegular) minLabel.textColor = handleColor maxLabel.frame = CGRect(x: 0, y: 5, width: backgroundView.frame.width, height: 20) maxLabel.text = textForPosition(max) maxLabel.textAlignment = NSTextAlignment.center maxLabel.font = UIFont.systemFont(ofSize: 11, weight: UIFontWeightRegular) maxLabel.textColor = handleColor currentPosLabel.frame = CGRect(x: handleView.frame.width, y: handleView.frame.origin.y + handleHeight*0.5/2, width: handleWidth, height: handleHeight * 1.5) currentPosLabel.text = "" currentPosLabel.textAlignment = NSTextAlignment.center currentPosLabel.textColor = UIColor.white handleLabel.font = UIFont.systemFont(ofSize: 13, weight: UIFontWeightBold) currentPosLabel.backgroundColor = tintColor currentPosLabel.alpha = 0.0 currentPosTriangle.frame = CGRect(x: -10, y: 10, width: currentPosLabel.frame.height-20, height: currentPosLabel.frame.height-20) currentPosTriangle.tintColor = tintColor currentPosTriangle.backgroundColor = UIColor.clear } open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { super.beginTracking(touch, with: event) UIView.animate(withDuration: 0.3, animations: { self.currentPosLabel.alpha = 1.0 }) return true } open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { super.continueTracking(touch, with: event) let _ = handlePosition let point = touch.location(in: sliderView) moveHandleToPoint(point) return true } open override func endTracking(_ touch: UITouch?, with event: UIEvent?) { super.endTracking(touch, with: event) let endPosition = handlePosition handlePosition = endPosition handleLabel.text = textForPosition(handlePosition) UIView.animate(withDuration: 0.3, animations: { self.currentPosLabel.alpha = 0.0 }) } open override func cancelTracking(with event: UIEvent?) { super.cancelTracking(with: event) } fileprivate func moveHandleToPoint(_ point:CGPoint) { var newY:CGFloat newY = point.y - CGFloat(handleView.frame.height/2) if newY < -handleHeight/2 { newY = -handleHeight/2 } else if newY > sliderView.frame.height - handleHeight/2 { newY = sliderView.frame.height - handleHeight/2 } handleView.frame.origin.y = CGFloat(newY) sliderFillView.frame = CGRect(x: 0 , y: CGFloat(newY) + handleHeight, width: sliderBackgroundView.frame.width, height: sliderBackgroundView.frame.height-handleView.frame.origin.y - handleHeight) currentPosLabel.frame = CGRect(x: handleView.frame.width, y: handleView.frame.origin.y + handleHeight*0.5/2, width: currentPosLabel.frame.width, height: currentPosLabel.frame.height) let newText = textForPosition(handlePosition) if handleLabel.text != newText { handleLabel.text = newText currentPosLabel.text = newText } } fileprivate func moveHandleToPosition(_ position:Double, animated:Bool = false) { if step == 0 { return } var goPosition = position if position >= max { goPosition = max } if position <= min { goPosition = min } let positionFromMin = (goPosition - min) / step let newY = CGFloat(minPosition - positionFromMin * stepheight) if animated { UIView.animate(withDuration: 0.3, animations: { self.handleView.frame.origin.y = newY - self.handleHeight/2 self.sliderFillView.frame = CGRect(x: 0 , y: CGFloat(newY) + self.handleHeight/2, width: self.sliderBackgroundView.frame.width, height: self.sliderBackgroundView.frame.height - self.handleView.frame.origin.y - self.handleHeight) self.currentPosLabel.frame = CGRect(x: self.handleView.frame.width, y: self.handleView.frame.origin.y + self.handleHeight*0.5/2, width: self.currentPosLabel.frame.width, height: self.currentPosLabel.frame.height) }) } else { self.handleView.frame.origin.y = newY - self.handleHeight/2 self.sliderFillView.frame.origin.y = CGFloat(newY) + self.handleHeight currentPosLabel.frame = CGRect(x: handleView.frame.width, y: handleView.frame.origin.y + handleHeight*0.5/2, width: currentPosLabel.frame.width, height: currentPosLabel.frame.height) } let newText = textForPosition(position) if handleLabel.text != newText { handleLabel.text = newText currentPosLabel.text = newText } } fileprivate func textForPosition(_ position:Double) -> String { if isFloatingPoint { return String(format: "%0.1f", arguments: [position]) } else { return String(format: "%0.0f", arguments: [position]) } } } class TriangleView : UIView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } override func draw(_ rect: CGRect) { let ctx : CGContext = UIGraphicsGetCurrentContext()! ctx.beginPath() ctx.move(to: CGPoint(x: rect.minX, y: rect.maxY/2.0)) ctx.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) ctx.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) ctx.closePath() ctx.setFillColor(tintColor.cgColor) ctx.fillPath() } }
mit
7d8a9d276eca328d8051b0e9ecdcd9cd
36.216438
244
0.635306
4.706861
false
false
false
false
olivier38070/OAuthSwift
OAuthSwiftDemo/ViewController.swift
2
42746
// // ViewController.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import OAuthSwift #if os(iOS) import UIKit class ViewController: UIViewController {} #elseif os(OSX) import AppKit class ViewController: NSViewController { let segueSemaphore = Semaphore() } #endif // MARK: - do authentification extension ViewController { func doAuthService(service: String) { guard var parameters = services[service] else { showAlertView("Miss configuration", message: "\(service) not configured") return } #if os(OSX) // Ask to user if Services.parametersEmpty(parameters) { dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier(ConsumerSegue, sender: self) } segueSemaphore.wait() if let key = segueSemaphore.key, secret = segueSemaphore.secret where !key.isEmpty && !secret.isEmpty { parameters["consumerKey"] = key parameters["consumerSecret"] = secret } } #endif if Services.parametersEmpty(parameters) { // no value to set let message = "\(service) seems to have not weel configured. \nPlease fill consumer key and secret into configuration file \(self.confPath)" print(message) showAlertView("Miss configuration", message: message) // TODO here ask for parameters instead } parameters["name"] = service switch service { case "Twitter": doOAuthTwitter(parameters) case "Flickr": doOAuthFlickr(parameters) case "Github": doOAuthGithub(parameters) case "Instagram": doOAuthInstagram(parameters) case "Foursquare": doOAuthFoursquare(parameters) case "Fitbit": doOAuthFitbit(parameters) case "Fitbit2": doOAuthFitbit2(parameters) case "Withings": doOAuthWithings(parameters) case "Linkedin": doOAuthLinkedin(parameters) case "Linkedin2": doOAuthLinkedin2(parameters) case "Dropbox": doOAuthDropbox(parameters) case "Dribbble": doOAuthDribbble(parameters) case "Salesforce": doOAuthSalesforce(parameters) case "BitBucket": doOAuthBitBucket(parameters) case "GoogleDrive": doOAuthGoogle(parameters) case "Smugmug": doOAuthSmugmug(parameters) case "Intuit": doOAuthIntuit(parameters) case "Zaim": doOAuthZaim(parameters) case "Tumblr": doOAuthTumblr(parameters) case "Slack": doOAuthSlack(parameters) case "Uber": doOAuthUber(parameters) case "Gitter": doOAuthGitter(parameters) case "Facebook": doOAuthFacebook(parameters) default: print("\(service) not implemented") } } func doOAuthTwitter(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://api.twitter.com/oauth/request_token", authorizeUrl: "https://api.twitter.com/oauth/authorize", accessTokenUrl: "https://api.twitter.com/oauth/access_token" ) //oauthswift.authorize_url_handler = get_url_handler() oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/twitter")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testTwitter(oauthswift) }, failure: { error in print(error.localizedDescription) } ) } func testTwitter(oauthswift: OAuth1Swift) { oauthswift.client.get("https://api.twitter.com/1.1/statuses/mentions_timeline.json", parameters: [:], success: { data, response in let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) print(jsonDict) }, failure: { error in print(error) }) } func doOAuthFlickr(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://www.flickr.com/services/oauth/request_token", authorizeUrl: "https://www.flickr.com/services/oauth/authorize", accessTokenUrl: "https://www.flickr.com/services/oauth/access_token" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/flickr")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testFlickr(oauthswift, consumerKey: serviceParameters["consumerKey"]!) }, failure: { error in print(error.localizedDescription) }) } func testFlickr (oauthswift: OAuth1Swift, consumerKey: String) { let url :String = "https://api.flickr.com/services/rest/" let parameters :Dictionary = [ "method" : "flickr.photos.search", "api_key" : consumerKey, "user_id" : "128483205@N08", "format" : "json", "nojsoncallback" : "1", "extras" : "url_q,url_z" ] oauthswift.client.get(url, parameters: parameters, success: { data, response in let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) print(jsonDict) }, failure: { error in print(error) }) } func doOAuthGithub(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://github.com/login/oauth/authorize", accessTokenUrl: "https://github.com/login/oauth/access_token", responseType: "code" ) let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/github")!, scope: "user,repo", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthSalesforce(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://login.salesforce.com/services/oauth2/authorize", accessTokenUrl: "https://login.salesforce.com/services/oauth2/token", responseType: "code" ) let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/salesforce")!, scope: "full", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthInstagram(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://api.instagram.com/oauth/authorize", responseType: "token" ) let state: String = generateStateWithLength(20) as String oauthswift.authorize_url_handler = get_url_handler() oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/instagram")!, scope: "likes+comments", state:state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testInstagram(oauthswift) }, failure: { error in print(error.localizedDescription) }) } func testInstagram(oauthswift: OAuth2Swift) { let url :String = "https://api.instagram.com/v1/users/1574083/?access_token=\(oauthswift.client.credential.oauth_token)" let parameters :Dictionary = Dictionary<String, AnyObject>() oauthswift.client.get(url, parameters: parameters, success: { data, response in let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) print(jsonDict) }, failure: { error in print(error) }) } func doOAuthFoursquare(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://foursquare.com/oauth2/authorize", responseType: "token" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/foursquare")!, scope: "", state: "", success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthFitbit(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://api.fitbit.com/oauth/request_token", authorizeUrl: "https://www.fitbit.com/oauth/authorize?display=touch", accessTokenUrl: "https://api.fitbit.com/oauth/access_token" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/fitbit")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthFitbit2(serviceParameters: [String:String]) { let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://www.fitbit.com/oauth2/authorize", accessTokenUrl: "https://api.fitbit.com/oauth2/token", responseType: "code" ) oauthswift.accessTokenBasicAuthentification = true let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/fitbit2")!, scope: "profile", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testFitbit2(oauthswift) }, failure: { error in print(error.localizedDescription) }) } func testFitbit2(oauthswift: OAuth2Swift) { oauthswift.client.get("https://api.fitbit.com/1/user/-/profile.json", parameters: [:], success: { data, response in let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) print(jsonDict) }, failure: { error in print(error.localizedDescription) }) } func doOAuthWithings(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://oauth.withings.com/account/request_token", authorizeUrl: "https://oauth.withings.com/account/authorize", accessTokenUrl: "https://oauth.withings.com/account/access_token" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/withings")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthLinkedin(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://api.linkedin.com/uas/oauth/requestToken", authorizeUrl: "https://api.linkedin.com/uas/oauth/authenticate", accessTokenUrl: "https://api.linkedin.com/uas/oauth/accessToken" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/linkedin")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testLinkedin(oauthswift) }, failure: { error in print(error.localizedDescription) }) } func testLinkedin(oauthswift: OAuth1Swift) { oauthswift.client.get("https://api.linkedin.com/v1/people/~", parameters: [:], success: { data, response in let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) print(dataString) }, failure: { error in print(error) }) } func doOAuthLinkedin2(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://www.linkedin.com/uas/oauth2/authorization", accessTokenUrl: "https://www.linkedin.com/uas/oauth2/accessToken", responseType: "code" ) let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: "http://oauthswift.herokuapp.com/callback/linkedin2")!, scope: "r_fullprofile", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testLinkedin2(oauthswift) }, failure: { error in print(error.localizedDescription) }) } func testLinkedin2(oauthswift: OAuth2Swift) { oauthswift.client.get("https://api.linkedin.com/v1/people/~?format=json", parameters: [:], success: { data, response in let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) print(dataString) }, failure: { error in print(error) }) } func doOAuthSmugmug(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "http://api.smugmug.com/services/oauth/getRequestToken.mg", authorizeUrl: "http://api.smugmug.com/services/oauth/authorize.mg", accessTokenUrl: "http://api.smugmug.com/services/oauth/getAccessToken.mg" ) oauthswift.allowMissingOauthVerifier = true // NOTE: Smugmug's callback URL is configured on their site and the one passed in is ignored. oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/smugmug")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthDropbox(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://www.dropbox.com/1/oauth2/authorize", accessTokenUrl: "https://api.dropbox.com/1/oauth2/token", responseType: "token" ) oauthswift.authorize_url_handler = get_url_handler() oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/dropbox")!, scope: "", state: "", success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) // Get Dropbox Account Info let parameters = Dictionary<String, AnyObject>() oauthswift.client.get("https://api.dropbox.com/1/account/info", parameters: parameters, success: { data, response in let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) print(jsonDict) }, failure: { error in print(error) }) }, failure: { error in print(error.localizedDescription) }) } func doOAuthDribbble(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://dribbble.com/oauth/authorize", accessTokenUrl: "https://dribbble.com/oauth/token", responseType: "code" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/dribbble")!, scope: "", state: "", success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) // Get User let parameters = Dictionary<String, AnyObject>() oauthswift.client.get("https://api.dribbble.com/v1/user?access_token=\(credential.oauth_token)", parameters: parameters, success: { data, response in let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) print(jsonDict) }, failure: { error in print(error) }) }, failure: { error in print(error.localizedDescription) }) } func doOAuthBitBucket(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://bitbucket.org/api/1.0/oauth/request_token", authorizeUrl: "https://bitbucket.org/api/1.0/oauth/authenticate", accessTokenUrl: "https://bitbucket.org/api/1.0/oauth/access_token" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/bitbucket")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testBitBucket(oauthswift) }, failure: { error in print(error.localizedDescription) }) } func testBitBucket(oauthswift: OAuth1Swift) { oauthswift.client.get("https://bitbucket.org/api/1.0/user", parameters: [:], success: { data, response in let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) print(dataString) }, failure: { error in print(error) }) } func doOAuthGoogle(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://accounts.google.com/o/oauth2/auth", accessTokenUrl: "https://accounts.google.com/o/oauth2/token", responseType: "code" ) // For googgle the redirect_uri should match your this syntax: your.bundle.id:/oauth2Callback // in plist define a url schem with: your.bundle.id: oauthswift.authorizeWithCallbackURL( NSURL(string: "https://oauthswift.herokuapp.com/callback/google")!, scope: "https://www.googleapis.com/auth/drive", state: "", success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) let parameters = Dictionary<String, AnyObject>() // Multi-part upload oauthswift.client.postImage("https://www.googleapis.com/upload/drive/v2/files", parameters: parameters, image: self.snapshot(), success: { data, response in let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) print("SUCCESS: \(jsonDict)") }, failure: { error in print(error) }) }, failure: { error in print("ERROR: \(error.localizedDescription)") }) } func doOAuthIntuit(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://oauth.intuit.com/oauth/v1/get_request_token", authorizeUrl: "https://appcenter.intuit.com/Connect/Begin", accessTokenUrl: "https://oauth.intuit.com/oauth/v1/get_access_token" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/intuit")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testIntuit(oauthswift, serviceParameters: serviceParameters) }, failure: { error in print(error.localizedDescription) }) } func testIntuit(oauthswift: OAuth1Swift, serviceParameters: [String:String]){ if let companyId = serviceParameters["companyId"] { oauthswift.client.get("https://sandbox-quickbooks.api.intuit.com/v3/company/\(companyId)/account/1", headers: ["Accept":"application/json"], success: { data, response in if let jsonDict = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) , dico = jsonDict as? [String: AnyObject] { print(dico) // XXX to generate with good date etc... let jsonUpdate = [ "Name": "Accounts Payable (A/P)", "SubAccount": false, "FullyQualifiedName": "Accounts Payable (A/P)", "Active": true, "Classification": "Liability", "Description": "Description added during update.", "AccountType": "Accounts Payable", "AccountSubType": "AccountsPayable", "CurrentBalance": -1091.23, "CurrentBalanceWithSubAccounts": -1091.23, "domain": "QBO", "sparse": false, "Id": "33", "SyncToken": "0", "MetaData": [ "CreateTime": "2014-09-12T10:12:02-07:00", "LastUpdatedTime": "2015-06-30T15:09:07-07:00" ] ] // FIXME #80 oauthswift.client.post("https://sandbox-quickbooks.api.intuit.com/v3/company/\(companyId)/account?operation=update", parameters: jsonUpdate, headers: ["Accept": "application/json", "Content-Type":"application/json"], success: { data, response in print(data) }, failure: { error in print(error) }) } else { print("no json response") } }, failure: { error in print(error) }) } } func doOAuthZaim(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "https://api.zaim.net/v2/auth/request", authorizeUrl: "https://auth.zaim.net/users/auth", accessTokenUrl: "https://api.zaim.net/v2/auth/access" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/zaim")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthTumblr(serviceParameters: [String:String]){ let oauthswift = OAuth1Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, requestTokenUrl: "http://www.tumblr.com/oauth/request_token", authorizeUrl: "http://www.tumblr.com/oauth/authorize", accessTokenUrl: "http://www.tumblr.com/oauth/access_token" ) oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/tumblr")!, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription) }) } func doOAuthSlack(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://slack.com/oauth/authorize", accessTokenUrl: "https://slack.com/api/oauth.access", responseType: "code" ) let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/slack")!, scope: "", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription, terminator: "") }) } func doOAuthUber(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://login.uber.com/oauth/authorize", accessTokenUrl: "https://login.uber.com/oauth/token", responseType: "code", contentType: "multipart/form-data" ) let state: String = generateStateWithLength(20) as String let redirectURL = "https://oauthswift.herokuapp.com/callback/uber".stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) oauthswift.authorizeWithCallbackURL( NSURL(string: redirectURL!)!, scope: "profile", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription, terminator: "") }) } func doOAuthGitter(serviceParameters: [String:String]){ let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://gitter.im/login/oauth/authorize", accessTokenUrl: "https://gitter.im/login/oauth/token", responseType: "code" ) #if os(iOS) if #available(iOS 9.0, *) { oauthswift.authorize_url_handler = SafariURLHandler(viewController: self) } #endif let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/gitter")!, scope: "flow", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) }, failure: { error in print(error.localizedDescription, terminator: "") }) } func doOAuthFacebook(serviceParameters: [String:String]) { let oauthswift = OAuth2Swift( consumerKey: serviceParameters["consumerKey"]!, consumerSecret: serviceParameters["consumerSecret"]!, authorizeUrl: "https://www.facebook.com/dialog/oauth", accessTokenUrl: "https://graph.facebook.com/oauth/access_token", responseType: "code" ) let state: String = generateStateWithLength(20) as String oauthswift.authorizeWithCallbackURL( NSURL(string: "https://oauthswift.herokuapp.com/callback/facebook")!, scope: "public_profile", state: state, success: { credential, response, parameters in self.showTokenAlert(serviceParameters["name"], credential: credential) self.testFacebook(oauthswift) }, failure: { error in print(error.localizedDescription, terminator: "") }) } func testFacebook(oauthswift: OAuth2Swift) { oauthswift.client.get("https://graph.facebook.com/me?", success: { data, response in let dataString = NSString(data: data, encoding: NSUTF8StringEncoding) print(dataString) }, failure: { error in print(error) }) } } let services = Services() let DocumentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let FileManager: NSFileManager = NSFileManager.defaultManager() extension ViewController { override func viewDidLoad() { super.viewDidLoad() // Load config from files initConf() // init now get_url_handler() #if os(iOS) self.navigationItem.title = "OAuth" let tableView: UITableView = UITableView(frame: self.view.bounds, style: .Plain) tableView.delegate = self tableView.dataSource = self self.view.addSubview(tableView) #endif } // MARK: utility methods var confPath: String { let appPath = "\(DocumentDirectory)/.oauth/" if !FileManager.fileExistsAtPath(appPath) { do { try FileManager.createDirectoryAtPath(appPath, withIntermediateDirectories: false, attributes: nil) }catch { print("Failed to create \(appPath)") } } return "\(appPath)Services.plist" } func initConf() { initConfOld() print("Load configuration from \n\(self.confPath)") // Load config from model file if let path = NSBundle.mainBundle().pathForResource("Services", ofType: "plist") { services.loadFromFile(path) if !FileManager.fileExistsAtPath(confPath) { do { try FileManager.copyItemAtPath(path, toPath: confPath) }catch { print("Failed to copy empty conf to\(confPath)") } } } services.loadFromFile(confPath) } func initConfOld() { // TODO Must be removed later services["Twitter"] = Twitter services["Salesforce"] = Salesforce services["Flickr"] = Flickr services["Github"] = Github services["Instagram"] = Instagram services["Foursquare"] = Foursquare services["Fitbit"] = Fitbit services["Withings"] = Withings services["Linkedin"] = Linkedin services["Linkedin2"] = Linkedin2 services["Dropbox"] = Dropbox services["Dribbble"] = Dribbble services["BitBucket"] = BitBucket services["GoogleDrive"] = GoogleDrive services["Smugmug "] = Smugmug services["Intuit"] = Intuit services["Zaim"] = Zaim services["Tumblr"] = Tumblr services["Slack"] = Slack services["Uber"] = Uber } func snapshot() -> NSData { #if os(iOS) UIGraphicsBeginImageContext(self.view.frame.size) self.view.layer.renderInContext(UIGraphicsGetCurrentContext()!) let fullScreenshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() UIImageWriteToSavedPhotosAlbum(fullScreenshot, nil, nil, nil) return UIImageJPEGRepresentation(fullScreenshot, 0.5)! #elseif os(OSX) let rep: NSBitmapImageRep = self.view.bitmapImageRepForCachingDisplayInRect(self.view.bounds)! self.view.cacheDisplayInRect(self.view.bounds, toBitmapImageRep:rep) return rep.TIFFRepresentation! #endif } func showAlertView(title: String, message: String) { #if os(iOS) let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) #elseif os(OSX) let alert = NSAlert() alert.messageText = title alert.informativeText = message alert.addButtonWithTitle("Close") alert.runModal() #endif } func showTokenAlert(name: String?, credential: OAuthSwiftCredential) { var message = "oauth_token:\(credential.oauth_token)" if !credential.oauth_token_secret.isEmpty { message += "\n\noauth_toke_secret:\(credential.oauth_token_secret)" } self.showAlertView(name ?? "Service", message: message) if let service = name { services.updateService(service, dico: ["authentified":"1"]) // TODO refresh graphic } } // MARK: create an optionnal internal web view to handle connection func createWebViewController() -> WebViewController { let controller = WebViewController() #if os(OSX) controller.view = NSView(frame: NSRect(x:0, y:0, width: 450, height: 500)) // needed if no nib or not loaded from storyboard controller.viewDidLoad() #endif return controller } func get_url_handler() -> OAuthSwiftURLHandlerType { // Create a WebViewController with default behaviour from OAuthWebViewController let url_handler = createWebViewController() #if os(OSX) self.addChildViewController(url_handler) // allow WebViewController to use this ViewController as parent to be presented #endif return url_handler #if os(OSX) // a better way is // - to make this ViewController implement OAuthSwiftURLHandlerType and assigned in oauthswift object /* return self */ // - have an instance of WebViewController here (I) or a segue name to launch (S) // - in handle(url) // (I) : affect url to WebViewController, and self.presentViewControllerAsModalWindow(self.webViewController) // (S) : affect url to a temp variable (ex: urlForWebView), then perform segue /* performSegueWithIdentifier("oauthwebview", sender:nil) */ // then override prepareForSegue() to affect url to destination controller WebViewController #endif } //(I) //let webViewController: WebViewController = createWebViewController() //(S) //var urlForWebView:?NSURL = nil #if os(OSX) override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) { if segue.identifier == ConsumerSegue { if let consumerController = segue.destinationController as? ConsumerViewController { consumerController.consumerDelegate = self } } else { super.prepareForSegue(segue, sender: sender) } } #endif } // MARK: - Table #if os(iOS) extension ViewController: UITableViewDelegate, UITableViewDataSource { // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return services.keys.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") let service = services.keys[indexPath.row] cell.textLabel?.text = service if let parameters = services[service] where Services.parametersEmpty(parameters) { cell.textLabel?.textColor = UIColor.redColor() } if let parameters = services[service], authentified = parameters["authentified"] where authentified == "1" { cell.textLabel?.textColor = UIColor.greenColor() } return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { let service: String = services.keys[indexPath.row] doAuthService(service) tableView.deselectRowAtIndexPath(indexPath, animated:true) } } #elseif os(OSX) extension ViewController: NSTableViewDataSource, NSTableViewDelegate { // MARK: NSTableViewDataSource func numberOfRowsInTableView(tableView: NSTableView) -> Int { return services.keys.count } func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { return services.keys[row] } func tableView(tableView: NSTableView, didAddRowView rowView: NSTableRowView, forRow row: Int) { let service = services.keys[row] if let parameters = services[service] where Services.parametersEmpty(parameters) { rowView.backgroundColor = NSColor.redColor() } if let parameters = services[service], authentified = parameters["authentified"] where authentified == "1" { rowView.backgroundColor = NSColor.greenColor() } } // MARK: NSTableViewDelegate func tableViewSelectionDidChange(notification: NSNotification) { if let tableView = notification.object as? NSTableView { let row = tableView.selectedRow if row != -1 { let service: String = services.keys[row] dispatch_async( dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { self.doAuthService(service) } tableView.deselectRow(row) } } } } #endif #if os(OSX) let ConsumerSegue = "consumer" extension ViewController: ConsumerViewControllerDelegate { func didKey(key: String, secret: String) { self.segueSemaphore.signal(key, secret: secret) } func didCancel() { self.segueSemaphore.signal() } } protocol ConsumerViewControllerDelegate { func didKey(key: String, secret: String) func didCancel() } class ConsumerViewController: ViewController { var consumerDelegate: ConsumerViewControllerDelegate? @IBOutlet var keyTextField: NSTextField! @IBOutlet var secretTextField: NSTextField! @IBAction func ok(sender: AnyObject?) { self.dismissController(sender) consumerDelegate?.didKey(keyTextField.stringValue, secret: secretTextField.stringValue) } @IBAction func cancel(sender: AnyObject?) { self.dismissController(sender) consumerDelegate?.didCancel() } } class Semaphore { let segueSemaphore = dispatch_semaphore_create(0) var key: String? var secret: String? func wait() { dispatch_semaphore_wait(segueSemaphore, DISPATCH_TIME_FOREVER) // wait user } func signal(key: String? = nil, secret: String? = nil) { self.key = key self.secret = secret dispatch_semaphore_signal(segueSemaphore) } } #endif
mit
a69078b938a08b1fc898304485090387
42.618367
182
0.597272
5.062293
false
false
false
false
Moya/Moya
Examples/Basic/ViewController.swift
1
4903
import UIKit import Moya import Combine import CombineMoya class ViewController: UITableViewController { var progressView = UIView() var repos = NSArray() var cancellable: AnyCancellable? override func viewDidLoad() { super.viewDidLoad() progressView.frame = CGRect(origin: .zero, size: CGSize(width: 0, height: 2)) progressView.backgroundColor = .blue navigationController?.navigationBar.addSubview(progressView) downloadRepositories("ashfurrow") } fileprivate func showAlert(_ title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) present(alertController, animated: true, completion: nil) } // MARK: - API Stuff func downloadRepositories(_ username: String) { gitHubProvider.request(.userRepositories(username)) { result in do { let response = try result.get() let value = try response.mapNSArray() self.repos = value self.tableView.reloadData() } catch { let printableError = error as CustomStringConvertible self.showAlert("GitHub Fetch", message: printableError.description) } } } func downloadZen() { cancellable = gitHubProvider.requestPublisher(.zen) .mapString() .sink(receiveCompletion: { _ in }, receiveValue: { message in self.showAlert("Zen", message: message) }) } func uploadGiphy() { giphyProvider.request(.upload(gif: Giphy.animatedBirdData), callbackQueue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } func downloadMoyaLogo() { gitHubUserContentProvider.request(.downloadMoyaWebContent("logo_github.png"), callbackQueue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } // MARK: - Progress Helpers lazy var progressClosure: ProgressBlock = { response in UIView.animate(withDuration: 0.3) { self.progressView.frame.size.width = self.view.frame.size.width * CGFloat(response.progress) } } lazy var progressCompletionClosure: Completion = { result in let color: UIColor switch result { case .success: color = .green case .failure: color = .red } UIView.animate(withDuration: 0.3) { self.progressView.backgroundColor = color self.progressView.frame.size.width = self.view.frame.size.width } UIView.animate(withDuration: 0.3, delay: 1, options: [], animations: { self.progressView.alpha = 0 }, completion: { _ in self.progressView.backgroundColor = .blue self.progressView.frame.size.width = 0 self.progressView.alpha = 1 } ) } // MARK: - User Interaction @IBAction func giphyWasPressed(_ sender: UIBarButtonItem) { uploadGiphy() } @IBAction func searchWasPressed(_ sender: UIBarButtonItem) { var usernameTextField: UITextField? let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { _ in if let username = usernameTextField?.text { self.downloadRepositories(username) } } promptController.addAction(okAction) promptController.addTextField { textField in usernameTextField = textField } present(promptController, animated: true, completion: nil) } @IBAction func zenWasPressed(_ sender: UIBarButtonItem) { downloadZen() } @IBAction func downloadWasPressed(_ sender: UIBarButtonItem) { downloadMoyaLogo() } // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { repos.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let repo = repos[indexPath.row] as? NSDictionary cell.textLabel?.text = repo?["name"] as? String return cell } }
mit
b2ed949def401cac6e453d84ea002087
33.286713
109
0.597389
5.429679
false
false
false
false
iOSDevLog/iOSDevLog
201. UI Test/Swift/Common/CheckBoxLayer.swift
1
2993
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A `CALayer` subclass that draws a check box within its layer. This is shared between ListerKit on iOS and OS X to to draw their respective `CheckBox` controls. */ import QuartzCore class CheckBoxLayer: CALayer { // MARK: Types struct SharedColors { static let defaultTintColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [0.5, 0.5, 0.5])! } // MARK: Properties var tintColor = SharedColors.defaultTintColor { didSet { setNeedsDisplay() } } var isChecked = false { didSet { setNeedsDisplay() } } var strokeFactor: CGFloat = 0.07 { didSet { setNeedsDisplay() } } var insetFactor: CGFloat = 0.17 { didSet { setNeedsDisplay() } } var markInsetFactor: CGFloat = 0.34 { didSet { setNeedsDisplay() } } // The method that does the heavy lifting of check box drawing code. override func drawInContext(context: CGContext) { super.drawInContext(context) let size = min(bounds.width, bounds.height) var transform = affineTransform() var xTranslate: CGFloat = 0 var yTranslate: CGFloat = 0 if bounds.size.width < bounds.size.height { yTranslate = (bounds.height - size) / 2.0 } else { xTranslate = (bounds.width - size) / 2.0 } transform = CGAffineTransformTranslate(transform, xTranslate, yTranslate) let strokeWidth: CGFloat = strokeFactor * size let checkBoxInset: CGFloat = insetFactor * size // Create the outer border for the check box. let outerDimension: CGFloat = size - 2.0 * checkBoxInset var checkBoxRect = CGRect(x: checkBoxInset, y: checkBoxInset, width: outerDimension, height: outerDimension) checkBoxRect = CGRectApplyAffineTransform(checkBoxRect, transform) // Make the desired width of the outer box. CGContextSetLineWidth(context, strokeWidth) // Set the tint color of the outer box. CGContextSetStrokeColorWithColor(context, tintColor) // Draw the outer box. CGContextStrokeRect(context, checkBoxRect) // Draw the inner box if it's checked. if isChecked { let markInset: CGFloat = markInsetFactor * size let markDimension: CGFloat = size - 2.0 * markInset var markRect = CGRect(x: markInset, y: markInset, width: markDimension, height: markDimension) markRect = CGRectApplyAffineTransform(markRect, transform) CGContextSetFillColorWithColor(context, tintColor) CGContextFillRect(context, markRect) } } }
mit
d93d0e9b5fcd52421afdcf2284f3fb72
29.520408
164
0.603477
5.148021
false
false
false
false
BjornRuud/HTTPSession
Pods/Swifter/Sources/Files.swift
4
2553
// // HttpHandlers+Files.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation public func shareFilesFromDirectory(_ directoryPath: String, defaults: [String] = ["index.html", "default.html"]) -> ((HttpRequest) -> HttpResponse) { return { r in guard let fileRelativePath = r.params.first else { return .notFound } if fileRelativePath.value.isEmpty { for path in defaults { if let file = try? (directoryPath + String.pathSeparator + path).openForReading() { return .raw(200, "OK", [:], { writer in try? writer.write(file) file.close() }) } } } if let file = try? (directoryPath + String.pathSeparator + fileRelativePath.value).openForReading() { return .raw(200, "OK", [:], { writer in try? writer.write(file) file.close() }) } return .notFound } } public func directoryBrowser(_ dir: String) -> ((HttpRequest) -> HttpResponse) { return { r in guard let (_, value) = r.params.first else { return HttpResponse.notFound } let filePath = dir + String.pathSeparator + value do { guard try filePath.exists() else { return .notFound } if try filePath.directory() { let files = try filePath.files() return scopes { html { body { table(files) { file in tr { td { a { href = r.path + "/" + file inner = file } } } } } } }(r) } else { guard let file = try? filePath.openForReading() else { return .notFound } return .raw(200, "OK", [:], { writer in try? writer.write(file) file.close() }) } } catch { return HttpResponse.internalServerError } } }
mit
4bb6c6d07a57b3edc5cbf0b052d9436a
32.578947
150
0.403605
5.596491
false
false
false
false
anjlab/JJ
JJ.playground/Sources/JJ.swift
1
25692
// // JJ.swift // Pods // // Created by Yury Korolev on 5/27/16. // // import UIKit private let _rfc3339DateFormatter: NSDateFormatter = _buildRfc3339DateFormatter() /** - Returns: **RFC 3339** date formatter */ private func _buildRfc3339DateFormatter() -> NSDateFormatter { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US") formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'" formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) return formatter } public extension String { /** Returns a date representation of a given **RFC 3339** string. If dateFromString: can not parse the string, returns `nil`. - Returns: A date representation of string. */ func asRFC3339Date() -> NSDate? { return _rfc3339DateFormatter.dateFromString(self) } } public extension NSDate { /** Returns a **RFC 3339** string representation of a given date formatted. - Returns: A **RFC 3339** string representation. */ func toRFC3339String() -> String { return _rfc3339DateFormatter.stringFromDate(self) } } /** */ public enum JJError: ErrorType, CustomStringConvertible { /** Throws on can't convert value on path */ case WrongType(v: AnyObject?, path: String, toType: String) /** Throws on can't find object on path */ case NotFound(path: String) public var description: String { switch self { case let .WrongType(v: v, path: path, toType: type): return "JJError.WrongType: Can't convert \(v) at path: '\(path)' to type '\(type)'" case let .NotFound(path: path): return "JJError.NotFound: No object at path: '\(path)'" } } } /** - Parameter v: `AnyObject` to parse - Returns: `JJVal` */ public func jj(v: AnyObject?) -> JJVal { return JJVal(v) } /** - Parameter decoder: `NSCoder` to decode - Returns: `JJDec` */ public func jj(decoder decoder: NSCoder) -> JJDec { return JJDec(decoder) } /** - Parameter encoder: `NSCoder` to encode - Returns: `JJEnc` */ public func jj(encoder encoder: NSCoder) -> JJEnc { return JJEnc(encoder) } /** Struct for store parsing `Array` */ public struct JJArr: CustomDebugStringConvertible, CustomPlaygroundQuickLookable { private let _path: String private let _v: [AnyObject] /** - Parameters: - v: [`AnyObject`] - path: `String` value of the path in original object - Returns: `JJArr` */ public init(_ v: [AnyObject], path: String) { _v = v _path = path } public subscript (index: Int) -> JJVal { return at(index) } /** - Parameter index: Index of element - Returns: `JJVal` or `JJVal(nil, path: newPath)` if `index` is out of `Array` */ public func at(index: Int) -> JJVal { let newPath = _path + "[\(index)]" if index >= 0 && index < _v.count { return JJVal(_v[index], path: newPath) } return JJVal(nil, path: newPath) } // MARK: extension point /** Raw value of stored `Array` */ public var raw: [AnyObject] { return _v } /** `String` value of the path in original object */ public var path: String { return _path } // MARK: Shortcusts /** `True` if raw value isn't equal `nil` */ public var exists: Bool { return true } /** The number of elements the `Array` stores */ public var count:Int { return _v.count } /** - Parameters: - space: space between parent elements of `Array` - spacer: space to embedded values - Returns: A textual representation of `Array` */ public func prettyPrint(space space: String = "", spacer: String = " ") -> String { if _v.count == 0 { return "[]" } var str = "[\n" let nextSpace = space + spacer for v in _v { str += "\(nextSpace)" + jj(v).prettyPrint(space: nextSpace, spacer: spacer) + ",\n" } str.removeAtIndex(str.endIndex.advancedBy(-2)) return str + "\(space)]" } /** A Textual representation of stored `Array` */ public var debugDescription: String { return prettyPrint() } //Playground Look private var descriptionTextView: UITextView { let textView = UITextView() textView.font = UIFont.systemFontOfSize(16) textView.text = prettyPrint() textView.sizeToFit() textView.scrollEnabled = true return textView } public func customPlaygroundQuickLook() -> PlaygroundQuickLook { return .View(descriptionTextView) } } /** Struct with optional raw value of `Array` */ public struct JJMaybeArr { private let _path: String private let _v: JJArr? public init(_ v: JJArr?, path: String) { _v = v _path = path } public func at(index: Int) -> JJVal { return _v?.at(index) ?? JJVal(nil, path: _path + "<nil>[\(index)]") } public subscript (index: Int) -> JJVal { return at(index) } public var exists: Bool { return _v != nil } // MARK: extension point public var raw: [AnyObject]? { return _v?.raw } public var path: String { return _path } } /** Struct for store parsing `Dictionary` */ public struct JJObj: CustomDebugStringConvertible, CustomPlaygroundQuickLookable { private let _path: String private let _v: [String: AnyObject] /** - Parameters: - v: [`String` : `AnyObject`] - path: `String` value of the path in original object - Returns: `JJObj` */ public init(_ v: [String: AnyObject], path: String) { _v = v _path = path } /** - Parameter key: Key of element of `Dictionary` - Returns: `JJVal` */ public func at(key: String) -> JJVal { let newPath = _path + ".\(key)" #if DEBUG if let msg = _v["$\(key)__depricated"] { debugPrint("WARNING:!!!!. Using depricated field \(newPath): \(msg)") } #endif return JJVal(_v[key], path: newPath) } /** - Parameter key: Key of element of `Dictionary` - Returns: `JJVal` */ public subscript (key: String) -> JJVal { return at(key) } // MARK: extension point /** Raw value of stored `Dictionary` */ public var raw: [String: AnyObject] { return _v } /** `String` value of the path in original object */ public var path: String { return _path } // Shortcusts /** `True` if raw value isn't equal `nil` */ public var exists: Bool { return true } /** The number of elements the `Dictionary` stores */ public var count:Int { return _v.count } /** - Parameters: - space: space between parent elements of `Dictionary` - spacer: space to embedded values - Returns: A textual representation of `Dictionary` */ public func prettyPrint(space space: String = "", spacer: String = " ") -> String { if _v.count == 0 { return "{}" } var str = "{\n" for (k, v) in _v { let nextSpace = space + spacer str += "\(nextSpace)\"\(k)\": \(jj(v).prettyPrint(space: nextSpace, spacer: spacer)),\n" } str.removeAtIndex(str.endIndex.advancedBy(-2)) return str + "\(space)}" } /** A Textual representation of stored `Dictionary` */ public var debugDescription: String { return prettyPrint() } //Playground Look private var descriptionTextView: UITextView { let textView = UITextView() textView.font = UIFont.systemFontOfSize(16) textView.text = prettyPrint() textView.sizeToFit() textView.scrollEnabled = true return textView } public func customPlaygroundQuickLook() -> PlaygroundQuickLook { return .View(descriptionTextView) } } /** Struct with optional raw value of `Dictionary` */ public struct JJMaybeObj { private let _path: String private let _v: JJObj? public init(_ v: JJObj?, path: String) { _v = v _path = path } public func at(key: String) -> JJVal { return _v?.at(key) ?? JJVal(nil, path: _path + "<nil>.\(key)") } public subscript (key: String) -> JJVal { return at(key) } // MARK: extension point public var raw: [String: AnyObject]? { return _v?.raw } public var path: String { return _path } // MARK: shortcusts public var exists: Bool { return _v != nil } } /** Struct for store parsed value Stored types: - `Bool` - `Int` - `UInt` - `Number` - `Float` - `Double` - `Dictionary` - `Array` - `String` - `Date` - `URL` - `Null` - `TimeZone` To get access to stored value use `raw` */ public struct JJVal: CustomDebugStringConvertible, CustomPlaygroundQuickLookable { private let _path: String private let _v: AnyObject? /** - Parameters: - v: `AnyObject` - path: `String` value of the path in original object - Returns: `JJVal` */ public init(_ v: AnyObject?, path: String = "<root>") { _v = v _path = path } // MARK: Bool /** Representation the raw value as `Bool`. If this impossible, it is set to `nil` */ public var asBool: Bool? { return _v as? Bool } /** Represent raw value as `Bool` - Parameter defaultValue: Returned `Bool` value, if impossible represent raw value as `Bool` (`false` by default) - Returns: `Bool` value */ public func toBool(@autoclosure defaultValue: () -> Bool = false) -> Bool { return asBool ?? defaultValue() } /** - Returns: `Bool` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `Bool` */ public func bool() throws -> Bool { if let x = _v as? Bool { return x } throw JJError.WrongType(v: _v, path: _path, toType: "Bool") } // MARK: Int /** Representation the raw value as `Int`. If this impossible, it is set to `nil` */ public var asInt: Int? { return _v as? Int } /** Represent raw value as `Int` - Parameter defaultValue: Returned `Int` value, if impossible represent raw value as `Int` (`0` by default) - Returns: `Int` value */ public func toInt(@autoclosure defaultValue: () -> Int = 0) -> Int { return asInt ?? defaultValue() } /** - Returns: `Int` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `Int` */ public func int() throws -> Int { if let x = asInt { return x } throw JJError.WrongType(v: _v, path: _path, toType: "Int") } // MARK: UInt /** Representation the raw value as `UInt`. If this impossible, it is set to `nil` */ public var asUInt: UInt? { return _v as? UInt } /** Represent raw value as `UInt` - Parameter defaultValue: Returned `UInt` value, if impossible represent raw value as `UInt` (`0` by default) - Returns: `UInt` value */ public func toUInt(@autoclosure defaultValue: () -> UInt = 0) -> UInt { return asUInt ?? defaultValue() } /** - Returns: `UInt` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `UInt` */ public func uInt() throws -> UInt { if let x = asUInt { return x } throw JJError.WrongType(v: _v, path: _path, toType: "UInt") } // MARK: NSNumber /** Representation the raw value as `NSNumber`. If this impossible, it is set to `nil` */ public var asNumber: NSNumber? { return _v as? NSNumber } /** Represent raw value as `NSNumber` - Parameter defaultValue: Returned `NSNumber` value, if impossible represent raw value as `NSNumber` (`0` by default) - Returns: `NSNumber` value */ public func toNumber(@autoclosure defaultValue: () -> NSNumber = 0) -> NSNumber { return asNumber ?? defaultValue() } /** - Returns: `NSNumber` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `NSNumber` */ public func number() throws -> NSNumber { if let x = asNumber { return x } throw JJError.WrongType(v: _v, path: _path, toType: "NSNumber") } // MARK: Float /** Representation the raw value as `Float`. If this impossible, it is set to `nil` */ public var asFloat: Float? { return _v as? Float } /** Represent raw value as `Float` - Parameter defaultValue: Returned `Float` value, if impossible represent raw value as `Float` (`0` by default) - Returns: `Float` value */ public func toFloat(@autoclosure defaultValue: () -> Float = 0) -> Float { return asFloat ?? defaultValue() } /** - Returns: `Float` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `Float` */ public func float() throws -> Float { if let x = asFloat { return x } throw JJError.WrongType(v: _v, path: _path,toType: "Float") } // MARK: Double /** Representation the raw value as `Double`. If this impossible, it is set to `nil` */ public var asDouble: Double? { return _v as? Double } /** Represent raw value as `Double` - Parameter defaultValue: Returned `Double` value, if impossible represent raw value as `Double` (`0` by default) - Returns: `Double` value */ public func toDouble(@autoclosure defaultValue: () -> Double = 0) -> Double { return asDouble ?? defaultValue() } /** - Returns: `Double` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `Double` */ public func double() throws -> Double { if let x = asDouble { return x } throw JJError.WrongType(v: _v, path: _path,toType: "Double") } // MARK: Object /** Representation the raw value as `JJObj`. If this impossible, it is set to `nil` */ public var asObj: JJObj? { if let obj = _v as? [String: AnyObject] { return JJObj(obj, path: _path) } return nil } /** Represent raw value as `JJObj` - Parameter defaultValue: Returned `JJObj` value, if impossible represent raw value as `JJObj` (`JJObj(nil, path: newPath)` by default) - Returns: `JJObj` */ public func toObj() -> JJMaybeObj { return JJMaybeObj(asObj, path: _path) } /** - Returns: `JJMaybeObj` value with stored optional `JJObj` of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `JJObj` */ public func obj() throws -> JJObj { if let obj = _v as? [String: AnyObject] { return JJObj(obj, path: _path) } throw JJError.WrongType( v: _v, path: _path, toType: "[String: AnyObject]") } // MARK: Array /** Representation the raw value as `JJArr`. If this impossible, it is set to `nil` */ public var asArr: JJArr? { if let arr = _v as? [AnyObject] { return JJArr(arr, path: _path) } return nil } /** Represent raw value as `JJArr` - Parameter defaultValue: Returned `JJArr` value, if impossible represent raw value as `JJArr` (`JJArr(nil, path: newPath)` by default) - Returns: `JJArr` */ public func toArr() -> JJMaybeArr { return JJMaybeArr(asArr, path: _path) } /** - Returns: `JJMaybeArr` value with stored optional `JJArr` of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `JJArr` */ public func arr() throws -> JJArr { guard let arr = _v as? [AnyObject] else { throw JJError.WrongType( v: _v, path: _path, toType: "[AnyObject]") } return JJArr(arr, path: _path) } // MARK: String /** Representation the raw value as `String`. If this impossible, it is set to `nil` */ public var asString: String? { return _v as? String } /** Represent raw value as `String` - Parameter defaultValue: Returned `String` value, if impossible represent raw value as `String` (Empty string by default) - Returns: `String` value */ public func toString(@autoclosure defaultValue: () -> String = "") -> String { return asString ?? defaultValue() } /** - Returns: `String` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `String` */ public func string() throws -> String { if let x = asString { return x } throw JJError.WrongType(v: _v, path: _path, toType: "String") } // MARK: Date /** Representation the raw value as `NSDate`. If this impossible, it is set to `nil` */ public var asDate: NSDate? { return asString?.asRFC3339Date() } /** - Returns: `NSDate` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `Date` */ public func date() throws -> NSDate { if let d = asString?.asRFC3339Date() { return d } else { throw JJError.WrongType(v: _v, path: _path, toType: "NSDate") } } // MARK: NSURL /** Representation the raw value as `NSURL`. If this impossible, it is set to `nil` */ public var asURL: NSURL? { if let s = asString, d = NSURL(string: s) { return d } else { return nil } } /** Represent raw value as `NSURL` - Parameter defaultValue: Returned `NSURL` value, if impossible represent raw value as `NSURL` (`NSURL()` by default) - Returns: `NSURL` value */ public func toURL(@autoclosure defaultValue: () -> NSURL = NSURL()) -> NSURL { return asURL ?? defaultValue() } /** - Returns: `NSURL` value of raw value - Throws: `JJError.wrongType` if the raw value can't represent as `NSURL` */ public func url() throws -> NSURL { if let s = asString, d = NSURL(string: s) { return d } else { throw JJError.WrongType(v: _v, path: _path, toType: "NSURL") } } // MARK: Null /** 'False' if raw value equal nil */ public var isNull: Bool { return _v === NSNull() } // MARK: NSTimeZone /** Representation the raw value as `NSTimeZone`. If this impossible, it is set to `nil` */ public var asTimeZone: NSTimeZone? { if let s = asString, d = NSTimeZone(name: s) { return d } else { return nil } } // MARK: Navigation as Object /** - Returns: JJVal by key if raw value can represent as JJObj */ public func at(key: String) -> JJVal { return toObj()[key] } public subscript (key: String) -> JJVal { return at(key) } // MARK: Navigation as Array /** - Returns: JJVal by index if raw value can represent as JJArr */ public func at(index: Int) -> JJVal { return toArr()[index] } public subscript (index: Int) -> JJVal { return at(index) } /** `True` if raw value isn't equal `nil` */ public var exists: Bool { return _v != nil } // MARK: extension point /** `String` value of the path in original object */ public var path: String { return _path } /** Raw value of stored object */ public var raw: AnyObject? { return _v } // MARK: pretty print /** - Parameters: - space: space between parent elements of `Array` - spacer: space to embedded values - Returns: A textual representation of stored value */ public func prettyPrint(space space: String = "", spacer: String = " ") -> String { if let arr = asArr { return arr.prettyPrint(space: space, spacer: spacer) } else if let obj = asObj { return obj.prettyPrint(space: space, spacer: spacer) } else if let s = asString { return "\"\(s)\"" } else if isNull { return "null" } else if let v = _v { return v.description } else { return "nil" } } // MARK: CustomDebugStringConvertible /** A Textual representation of stored value */ public var debugDescription: String { return prettyPrint() } //Playground Look private var descriptionTextView: UITextView { let textView = UITextView() textView.font = UIFont.systemFontOfSize(16) textView.text = prettyPrint() textView.sizeToFit() textView.scrollEnabled = true return textView } public func customPlaygroundQuickLook() -> PlaygroundQuickLook { return .View(descriptionTextView) } } /** Struct to encode `NSCoder` values */ public struct JJEnc { private let _enc: NSCoder /** - Parameter enc: `NSCoder` - Returns: `JJEnc` */ public init(_ enc: NSCoder) { _enc = enc } /** Put `Int` value - Parameters: - v: `Int` value - at: `String` value of key */ public func put(v:Int, at: String) { _enc.encodeInt32(Int32(v), forKey: at) } /** Put `Bool` value - Parameters: - v: `Bool` value - at: `String` value of key */ public func put(v:Bool, at: String) { _enc.encodeBool(v, forKey: at) } /** Put `AnyObject` value - Parameters: - v: `AnyObject` value - at: `String` value of key */ public func put(v:AnyObject?, at: String) { _enc.encodeObject(v, forKey: at) } } public struct JJDecVal { private let _key: String private let _dec: NSCoder /** - Parameters: - dec: `NSCoder` to decode - key: `String` value of key */ public init(dec: NSCoder, key: String) { _key = key _dec = dec } /** - Returns: `String` value of encoded value - Throws: `JJError.wrongType` if the encoded value can't decoded to `String` */ public func string() throws -> String { let v = _dec.decodeObjectForKey(_key) if let x = v as? String { return x } throw JJError.WrongType(v: v, path: _key, toType: "String") } /** Decode the encoded value as `String`. If this impossible, it is set to `nil` */ public var asString: String? { return _dec.decodeObjectForKey(_key) as? String } /** - Returns: `Int` value of encoded value - Throws: `JJError.wrongType` if the encoded value can't decoded to `Int` */ public func int() throws -> Int { return Int(_dec.decodeInt32ForKey(_key)) } /** Decode the encoded value as `Int`. If this impossible, it is set to `nil` */ public var asInt: Int? { return _dec.decodeObjectForKey(_key) as? Int } /** Decode the encoded value as `NSDate`. If this impossible, it is set to `nil` */ public var asDate: NSDate? { return _dec.decodeObjectForKey(_key) as? NSDate } /** Decode the encoded value as `NSURL`. If this impossible, it is set to `nil` */ public var asURL: NSURL? { return _dec.decodeObjectForKey(_key) as? NSURL } /** Decode the encoded value as `NSTimeZone`. If this impossible, it is set to `nil` */ public var asTimeZone: NSTimeZone? { return _dec.decodeObjectForKey(_key) as? NSTimeZone } /** - Returns: `Bool` value of encoded value - Throws: `JJError.wrongType` if the encoded value can't decoded to `Bool` */ public func bool() throws -> Bool { return _dec.decodeBoolForKey(_key) } /** Decode raw value to `Bool` - Returns: `Bool` value */ public func toBool() -> Bool { return _dec.decodeBoolForKey(_key) } /** Decode the encoded value as generic value. If this impossible, it is set to `nil` */ public func decodeAs<T: NSCoding>() -> T? { return _dec.decodeObjectForKey(_key) as? T } /** - Returns: generic value of encoded value - Throws: `JJError.wrongType` if the encoded value can't decoded to needed type */ public func decode<T: NSCoding>() throws -> T { let obj = _dec.decodeObjectForKey(_key) if let v:T = obj as? T { return v } // TODO: find a way to get type throw JJError.WrongType(v: obj, path: _key, toType: "T") } /** - Returns: `NSDate` value of encoded value - Throws: `JJError.wrongType` if the encoded value can't decoded to `NSDate` */ public func date() throws -> NSDate { let v = _dec.decodeObjectForKey(_key) if let x = v as? NSDate { return x } throw JJError.WrongType(v: v, path: _key, toType: "NSDate") } // extension point /** `NSCoder` */ public var decoder: NSCoder { return _dec } /** Key of encoded value */ public var key: String { return _key } } public struct JJDec { private let _dec: NSCoder /** - Parameter dec: `NSCoder` - Returns: `JJDec` */ public init(_ dec: NSCoder) { _dec = dec } public subscript (key: String) -> JJDecVal { return JJDecVal(dec: _dec, key: key) } }
mit
4df6cae11ac989f8cfa2208d746366a4
28.463303
140
0.575471
4.066477
false
false
false
false
kaneshin/IcoMoonKit
Example/Example iOS/ViewController.swift
1
1898
// ViewController.swift // // Copyright (c) 2015 Shintaro Kaneko // // 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 class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let frame = CGRect(x: 0, y: 0, width: 200, height: 200) var imageView = UIImageView(frame: frame) imageView.center = self.view.center var feather = FeatherGlyph.AirPlay(size: 140, color: UIColor.whiteColor()) feather.color = UIColor.blackColor() feather.backgroundColor = UIColor.whiteColor() imageView.image = feather.image(size: frame.size) imageView.contentMode = UIViewContentMode.Center self.view.addSubview(imageView) var label = UILabel(frame: frame) label.attributedText = feather.attributedText self.view.addSubview(label) } }
mit
ef15ada08dc252acc464e2033f59832f
41.177778
82
0.726027
4.54067
false
false
false
false
wuyezhiguhun/DDMusicFM
DDMusicFM/DDFound/Controller/DDFindRecommendController.swift
1
8344
// // DDFindRecommendController.swift // DDMusicFM // // Created by 王允顶 on 17/9/10. // Copyright © 2017年 王允顶. All rights reserved. // // 推荐 import UIKit import SnapKit let kSectionEditCommen = 0 //小编推荐 let kSectionLive = 1 //现场直播 let kSectionGuess = 2 //猜你喜欢 let kSectionCityColumn = 3 //城市歌单 let kSectionSpecial = 4 //精品听单 let kSectionAdvertise = 5 //推广 let kSectionHotCommends = 6 //热门推荐 let kSectionMore = 7 //更多分类 let findStyleFeeCell = "DDFindStyleFeeCell" let findStyleLiveCell = "DDFindStyleLiveCell" let findStyleSpecialCell = "DDFindStyleSpecialCell" let findStyleMoreCell = "DDFindStyleMoreCell" class DDFindRecommendController: DDFindBaseViewController, UITableViewDelegate, UITableViewDataSource, DDRankNetworkingDelegate, DDFindStyleFeeCellDelegate { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = DDColorHex(0xf3f3f3) self.view.addSubview(self.tableView) self.addViewConstrains() self.rankNetworking.requestRankresponse() self.rankNetworking.hotAndGuessNetworking() } func addViewConstrains() -> Void { self.tableView.snp.makeConstraints { (make) in make.top.equalTo(self.view).offset(0) make.left.equalTo(self.view).offset(0) make.right.equalTo(self.view).offset(0) make.bottom.equalTo(self.view).offset(-49) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: == DDFindStyleFeeCellDelegate == func styleFellCellMoreButtonTouch(_ styleFee: DDFindStyleFeeCell) { } //MARK: == UITableViewDataSource == func numberOfSections(in tableView: UITableView) -> Int { return self.viewModel.numberOfSections() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.viewModel.numberOfItemsInSection(section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == kSectionEditCommen { var cell = tableView.dequeueReusableCell(withIdentifier: findStyleFeeCell) if cell == nil { cell = DDFindStyleFeeCell(style: UITableViewCellStyle.default, reuseIdentifier: findStyleFeeCell) } (cell as! DDFindStyleFeeCell).delegate = self (cell as! DDFindStyleFeeCell).setRecommend((self.viewModel.recommendModel?.editorRecommendAlbums!)!) return cell! }else if indexPath.section == kSectionLive { var cell = tableView.dequeueReusableCell(withIdentifier: findStyleLiveCell) if cell == nil { cell = DDFindStyleLiveCell(style: UITableViewCellStyle.default, reuseIdentifier: findStyleLiveCell) } return cell! }else if indexPath.section == kSectionGuess { var cell = tableView.dequeueReusableCell(withIdentifier: findStyleFeeCell) if cell == nil { cell = DDFindStyleFeeCell(style: UITableViewCellStyle.default, reuseIdentifier: findStyleFeeCell) } return cell! }else if indexPath.section == kSectionCityColumn { var cell = tableView.dequeueReusableCell(withIdentifier: findStyleFeeCell) if cell == nil { cell = DDFindStyleFeeCell(style: UITableViewCellStyle.default, reuseIdentifier: findStyleFeeCell) } (cell as! DDFindStyleFeeCell).setCityColumn((self.viewModel.hotGuessModel?.cityColumn)!) return cell! }else if indexPath.section == kSectionSpecial { var cell = tableView.dequeueReusableCell(withIdentifier: findStyleSpecialCell) if cell == nil { cell = DDFindStyleSpecialCell(style: UITableViewCellStyle.default, reuseIdentifier: findStyleSpecialCell) } return cell! }else if indexPath.section == kSectionAdvertise { return UITableViewCell() }else if indexPath.section == kSectionHotCommends { var cell = tableView.dequeueReusableCell(withIdentifier: findStyleFeeCell) if cell == nil { cell = DDFindStyleFeeCell(style: UITableViewCellStyle.default, reuseIdentifier: findStyleFeeCell) } let itemModel: DDHotRecommendItemModel = self.viewModel.hotGuessModel?.hotRecommends?.list?.object(at: indexPath.row) as! DDHotRecommendItemModel (cell as! DDFindStyleFeeCell).setHotRecommedItem(itemModel) return cell! }else if indexPath.section == kSectionMore { var cell = tableView.dequeueReusableCell(withIdentifier: findStyleMoreCell) if cell == nil { cell = DDFindStyleMoreCell(style: UITableViewCellStyle.default, reuseIdentifier: findStyleMoreCell) } return cell! } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.viewModel.heightForRowAtIndex(indexPath) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } //MARK: == DDRankNetworkingDelegate == func rankNetworkingStart() { } func rankNetworkingSuccess(_ recommendModel: DDFindRecommendModel) { self.viewModel.recommendModel = recommendModel self.headerView.model = recommendModel.focusImages! //开启头部定时器 DDFindRecommendHelper.helper.startHeadTimer() self.tableView.reloadData() } func rankNetworkingFailure() { } func hotAndGuessNetworkingStsrt() { } func hotAndGuessNetworkingFailure() { } func hotAndGuessNetworkingSuccess(_ hotGuessModel: DDFindHotGuessModel) { self.viewModel.hotGuessModel = hotGuessModel self.headerView.discoverModel = hotGuessModel.discoveryColumns! self.tableView.reloadData() } //MARK: == get 函数 == var _tableView: UITableView? var tableView: UITableView { get { if _tableView == nil { _tableView = UITableView() _tableView?.delegate = self _tableView?.dataSource = self _tableView?.separatorStyle = UITableViewCellSeparatorStyle.none _tableView?.tableHeaderView = self.headerView _tableView?.backgroundColor = UIColor.clear } return _tableView! } set { _tableView = tableView } } var _headerView: DDFindRecomHeader? var headerView: DDFindRecomHeader { get { if _headerView == nil { _headerView = DDFindRecomHeader.findRecomHeader _headerView?.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 250) _headerView?.backgroundColor = UIColor.clear } return _headerView! } set { _headerView = newValue } } var _rankNetworking: DDRankNetworking? var rankNetworking: DDRankNetworking { get { if _rankNetworking == nil { _rankNetworking = DDRankNetworking() _rankNetworking?.delegate = self } return _rankNetworking! } set { _rankNetworking = newValue } } var _viewModel: DDFindRecomViewModel? var viewModel: DDFindRecomViewModel { get { if _viewModel == nil { _viewModel = DDFindRecomViewModel() } return _viewModel! } set { _viewModel = newValue } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
ae2fd65eedd393ba789e1bf7dadcc0c3
37.900943
157
0.638171
4.70988
false
false
false
false
richardpiazza/SOSwift
Sources/SOSwift/Product.swift
1
11982
import Foundation /// Any offered product or service. /// /// ## For Example /// * A pair of shoes /// * A concert ticket /// * The rental of a car /// * A haircut; or /// * An episode of a TV show streamed online. public class Product: Thing { /// A property-value pair representing an additional characteristics of the entitity. /// /// ## For Example /// A product feature or another characteristic for which there is no matching property in schema.org. /// /// - note: Publishers should be aware that applications designed to use specific schema.org properties /// [http://schema.org/width](http://schema.org/width), /// [http://schema.org/color](http://schema.org/color), /// [http://schema.org/gtin13](http://schema.org/gtin13), /// etc. will typically expect such data to be provided using those properties, rather than using the generic property/value mechanism. public var additionalProperty: PropertyValue? /// The overall rating, based on a collection of reviews or ratings, of the item. public var aggregateRating: AggregateRating? /// An intended audience, i.e. a group for whom something was created. public var audience: Audience? /// An award won by or for this item. public var award: String? /// The brand(s) associated with a product or service, or the brand(s) maintained by an organization or business person. public var brand: BrandOrOrganization? /// A category for the item. Greater signs or slashes can be used to informally indicate a category hierarchy. public var category: ThingOrText? /// The color of the product. public var color: String? /// The depth of the item. public var depth: DistanceOrQuantitativeValue? /// The GTIN-12 code of the product, or the product to which the offer refers. /// /// The GTIN-12 is the 12-digit GS1 Identification Key composed of a U.P.C. Company Prefix, Item Reference, and Check Digit used to identify trade items. public var gtin12: String? /// The GTIN-13 code of the product, or the product to which the offer refers. /// /// This is equivalent to 13-digit ISBN codes and EAN UCC-13. Former 12-digit UPC codes can be converted into a GTIN-13 code by simply adding a /// preceeding zero. public var gtin13: String? /// The GTIN-14 code of the product, or the product to which the offer refers. public var gtin14: String? /// The GTIN-8 code of the product, or the product to which the offer refers. /// /// This code is also known as EAN/UCC-8 or 8-digit EAN. public var gtin8: String? /// The height of the item. public var height: DistanceOrQuantitativeValue? /// A pointer to another product (or multiple products) for which this product is an accessory or spare part. public var accessoryOrSparePartFor: [Product]? /// A pointer to another product (or multiple products) for which this product is a consumable. public var consumableFor: [Product]? /// A pointer to another, somehow related product (or multiple products). public var relatedTo: [ProductOrService]? /// A pointer to another, functionally similar product (or multiple products). public var similarTo: [ProductOrService]? /// A predefined value from OfferItemCondition or a textual description of the condition of the product or service, or the products or services included in the /// offer. public var itemCondition: OfferItemCondition? /// An associated logo. public var logo: ImageObjectOrURL? /// The manufacturer of the product. public var manufacturer: Organization? /// A material that something is made from. /// /// ## For Example /// * Leather /// * Wool /// * Cotton /// * Paper public var material: ProductOrURLOrText? /// The model of the product. /// /// Use with the URL of a ProductModel or a textual representation of the model identifier. The URL of the ProductModel can be from an external source. It is /// recommended to additionally provide strong product identifiers via the gtin8/gtin13/gtin14 and mpn properties. public var model: ProductModelOrText? /// The Manufacturer Part Number (MPN) of the product, or the product to which the offer refers. public var mpn: String? /// An offer to provide this item—for example, an offer to sell a product, rent the DVD of a movie, perform a service, or give away tickets to an event. public var offers: [Offer]? /// The product identifier, such as ISBN. /// /// ## For Example /// metaitemprop="productID" content="isbn:123-456-789" public var productID: String? /// The date of production of the item. public var productionDate: DateOnly? /// The date the item was purchased by the current owner. public var purchaseDate: DateOnly? /// The release date of a product or product model. /// /// This can be used to distinguish the exact variant of a product. public var releaseDate: DateOnly? /// A review of the item. public var reviews: [Review]? /// The Stock Keeping Unit (SKU), i.e. a merchant-specific identifier for a product or service, or the product to which the offer refers. public var sku: String? /// The weight of the product or person. public var weight: QuantitativeValue? /// The width of the item. public var width: DistanceOrQuantitativeValue? internal enum ProductCodingKeys: String, CodingKey { case additionalProperty case aggregateRating case audience case award case brand case category case color case depth case gtin12 case gtin13 case gtin14 case gtin8 case height case accessoryOrSparePartFor = "isAccessoryOrSparePartFor" case consumableFor = "isConsumableFor" case relatedTo = "isRelatedTo" case similarTo = "isSimilarTo" case itemCondition case logo case manufacturer case material case model case mpn case offers case productID case productionDate case purchaseDate case releaseDate case reviews = "review" case sku case weight case width } public override init() { super.init() } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: ProductCodingKeys.self) additionalProperty = try container.decodeIfPresent(PropertyValue.self, forKey: .additionalProperty) aggregateRating = try container.decodeIfPresent(AggregateRating.self, forKey: .aggregateRating) audience = try container.decodeIfPresent(Audience.self, forKey: .audience) award = try container.decodeIfPresent(String.self, forKey: .award) brand = try container.decodeIfPresent(BrandOrOrganization.self, forKey: .brand) category = try container.decodeIfPresent(ThingOrText.self, forKey: .category) color = try container.decodeIfPresent(String.self, forKey: .color) depth = try container.decodeIfPresent(DistanceOrQuantitativeValue.self, forKey: .depth) gtin12 = try container.decodeIfPresent(String.self, forKey: .gtin12) gtin13 = try container.decodeIfPresent(String.self, forKey: .gtin13) gtin14 = try container.decodeIfPresent(String.self, forKey: .gtin14) gtin8 = try container.decodeIfPresent(String.self, forKey: .gtin8) height = try container.decodeIfPresent(DistanceOrQuantitativeValue.self, forKey: .height) accessoryOrSparePartFor = try container.decodeIfPresent([Product].self, forKey: .accessoryOrSparePartFor) consumableFor = try container.decodeIfPresent([Product].self, forKey: .consumableFor) relatedTo = try container.decodeIfPresent([ProductOrService].self, forKey: .relatedTo) similarTo = try container.decodeIfPresent([ProductOrService].self, forKey: .similarTo) itemCondition = try container.decodeIfPresent(OfferItemCondition.self, forKey: .itemCondition) logo = try container.decodeIfPresent(ImageObjectOrURL.self, forKey: .logo) manufacturer = try container.decodeIfPresent(Organization.self, forKey: .manufacturer) material = try container.decodeIfPresent(ProductOrURLOrText.self, forKey: .material) model = try container.decodeIfPresent(ProductModelOrText.self, forKey: .model) mpn = try container.decodeIfPresent(String.self, forKey: .mpn) offers = try container.decodeIfPresent([Offer].self, forKey: .offers) productID = try container.decodeIfPresent(String.self, forKey: .productID) productionDate = try container.decodeIfPresent(DateOnly.self, forKey: .productionDate) purchaseDate = try container.decodeIfPresent(DateOnly.self, forKey: .purchaseDate) releaseDate = try container.decodeIfPresent(DateOnly.self, forKey: .releaseDate) reviews = try container.decodeIfPresent([Review].self, forKey: .reviews) sku = try container.decodeIfPresent(String.self, forKey: .sku) weight = try container.decodeIfPresent(QuantitativeValue.self, forKey: .weight) width = try container.decodeIfPresent(DistanceOrQuantitativeValue.self, forKey: .width) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: ProductCodingKeys.self) try container.encodeIfPresent(additionalProperty, forKey: .additionalProperty) try container.encodeIfPresent(aggregateRating, forKey: .aggregateRating) try container.encodeIfPresent(audience, forKey: .audience) try container.encodeIfPresent(award, forKey: .award) try container.encodeIfPresent(brand, forKey: .brand) try container.encodeIfPresent(category, forKey: .category) try container.encodeIfPresent(color, forKey: .color) try container.encodeIfPresent(depth, forKey: .depth) try container.encodeIfPresent(gtin12, forKey: .gtin12) try container.encodeIfPresent(gtin13, forKey: .gtin13) try container.encodeIfPresent(gtin14, forKey: .gtin14) try container.encodeIfPresent(gtin8, forKey: .gtin8) try container.encodeIfPresent(height, forKey: .height) try container.encodeIfPresent(accessoryOrSparePartFor, forKey: .accessoryOrSparePartFor) try container.encodeIfPresent(consumableFor, forKey: .consumableFor) try container.encodeIfPresent(relatedTo, forKey: .relatedTo) try container.encodeIfPresent(similarTo, forKey: .similarTo) try container.encodeIfPresent(itemCondition, forKey: .itemCondition) try container.encodeIfPresent(logo, forKey: .logo) try container.encodeIfPresent(manufacturer, forKey: .manufacturer) try container.encodeIfPresent(material, forKey: .material) try container.encodeIfPresent(model, forKey: .model) try container.encodeIfPresent(mpn, forKey: .mpn) try container.encodeIfPresent(offers, forKey: .offers) try container.encodeIfPresent(productID, forKey: .productID) try container.encodeIfPresent(productionDate, forKey: .productionDate) try container.encodeIfPresent(purchaseDate, forKey: .purchaseDate) try container.encodeIfPresent(releaseDate, forKey: .releaseDate) try container.encodeIfPresent(reviews, forKey: .reviews) try container.encodeIfPresent(sku, forKey: .sku) try container.encodeIfPresent(weight, forKey: .weight) try container.encodeIfPresent(width, forKey: .width) try super.encode(to: encoder) } }
mit
16d2ff728a3485bb91cf7714a57d38ec
45.796875
163
0.691486
4.607692
false
false
false
false
liuchuo/SAMS
SAMS0/SAMS0/ResultByCourseNameTableViewController.swift
1
4988
// // ResultByCourseNameTableViewController.swift // SAMS0 // // Created by ChenXin on 2016/11/23. // Copyright © 2016年 ChenXin. All rights reserved. // import UIKit class ResultByCourseNameTableViewController: UITableViewController { // 数据源 var snoArr : Array<String> = [] var snameArr : Array<String> = [] var scoreArr : Array<String> = [] var SearchCourseName : String = "" 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() loadTableViewData() } override func viewWillAppear(_ animated: Bool) { loadTableViewData() } func loadTableViewData() { let querySQL = "SELECT sno, sname, os, dataStructure, english, history, java, math, pe, softwareEngineer FROM 't_stuInfo';" let resultDictArr = SQLManager.shareInstance().queryDataBase(querySQL: querySQL) snoArr = [] snameArr = [] scoreArr = [] for dict in resultDictArr! { snoArr.append(dict["sno"]! as! String) snameArr.append(dict["sname"]! as! String) scoreArr.append(dict["\(SearchCourseName)"]! as! String) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return snoArr.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) // Configure the cell... let snoLabel = cell.viewWithTag(103) as! UILabel snoLabel.text = snoArr[indexPath.row] let snameLabel = cell.viewWithTag(104) as! UILabel snameLabel.text = snameArr[indexPath.row] let scoreLabel = cell.viewWithTag(105) as! UILabel scoreLabel.text = scoreArr[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let editByCourseName = storyboard?.instantiateViewController(withIdentifier: "editByCourseName") as! EditScoreByCourseNameViewController editByCourseName.sno = snoArr[indexPath.row] editByCourseName.courseName = SearchCourseName present(editByCourseName, animated: true, completion: nil) } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source let sno = snoArr[indexPath.row] let deleteSQL = "DELETE FROM 't_StuInfo' WHERE sno = '\(sno)';" if SQLManager.shareInstance().execSQL(SQL: deleteSQL) == true { print("删除成功!~") } loadTableViewData() } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
90155902bc8a8528eb6243cab4c0e147
34.748201
144
0.653653
4.857283
false
false
false
false
hellogaojun/Swift-coding
swift学习教材案例/GuidedTour-2.0.playground/Pages/Enumerations and Structures.xcplaygroundpage/Contents.swift
2
4774
//: ## Enumerations and Structures //: //: Use `enum` to create an enumeration. Like classes and all other named types, enumerations can have methods associated with them. //: enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.rawValue) } } } let ace = Rank.Ace let aceRawValue = ace.rawValue //: > **Experiment**: //: > Write a function that compares two `Rank` values by comparing their raw values. //: //: In the example above, the raw-value type of the enumeration is `Int`, so you only have to specify the first raw value. The rest of the raw values are assigned in order. You can also use strings or floating-point numbers as the raw type of an enumeration. Use the `rawValue` property to access the raw value of an enumeration member. //: //: Use the `init?(rawValue:)` initializer to make an instance of an enumeration from a raw value. //: if let convertedRank = Rank(rawValue: 3) { let threeDescription = convertedRank.simpleDescription() } //: The member values of an enumeration are actual values, not just another way of writing their raw values. In fact, in cases where there isn’t a meaningful raw value, you don’t have to provide one. //: enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription() //: > **Experiment**: //: > Add a `color()` method to `Suit` that returns “black” for spades and clubs, and returns “red” for hearts and diamonds. //: //: Notice the two ways that the `Hearts` member of the enumeration is referred to above: When assigning a value to the `hearts` constant, the enumeration member `Suit.Hearts` is referred to by its full name because the constant doesn’t have an explicit type specified. Inside the switch, the enumeration member is referred to by the abbreviated form `.Hearts` because the value of `self` is already known to be a suit. You can use the abbreviated form anytime the value’s type is already known. //: //: Use `struct` to create a structure. Structures support many of the same behaviors as classes, including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference. //: struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() //: > **Experiment**: //: > Add a method to `Card` that creates a full deck of cards, with one card of each combination of rank and suit. //: //: An instance of an enumeration member can have values associated with the instance. Instances of the same enumeration member can have different values associated with them. You provide the associated values when you create the instance. Associated values and raw values are different: The raw value of an enumeration member is the same for all of its instances, and you provide the raw value when you define the enumeration. //: //: For example, consider the case of requesting the sunrise and sunset time from a server. The server either responds with the information or it responds with some error information. //: enum ServerResponse { case Result(String, String) case Error(String) } let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.") switch success { case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error(error): let serverResponse = "Failure... \(error)" } //: > **Experiment**: //: > Add a third case to `ServerResponse` and to the switch. //: //: Notice how the sunrise and sunset times are extracted from the `ServerResponse` value as part of matching the value against the switch cases. //: //: [Previous](@previous) | [Next](@next)
apache-2.0
40940b16e18f50c43d58c32b48dcab9f
44.759615
495
0.685792
4.518519
false
false
false
false
Quick/Nimble
Sources/Nimble/Matchers/Contain.swift
8
5744
#if canImport(Foundation) import Foundation #endif /// A Nimble matcher that succeeds when the actual sequence contains the expected values. public func contain<S: Sequence>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable { return contain(items) } /// A Nimble matcher that succeeds when the actual sequence contains the expected values. public func contain<S: Sequence>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable { return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in guard let actual = try actualExpression.evaluate() else { return .fail } let matches = items.allSatisfy { return actual.contains($0) } return PredicateStatus(bool: matches) } } /// A Nimble matcher that succeeds when the actual set contains the expected values. public func contain<S: SetAlgebra>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable { return contain(items) } /// A Nimble matcher that succeeds when the actual set contains the expected values. public func contain<S: SetAlgebra>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable { return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in guard let actual = try actualExpression.evaluate() else { return .fail } let matches = items.allSatisfy { return actual.contains($0) } return PredicateStatus(bool: matches) } } /// A Nimble matcher that succeeds when the actual set contains the expected values. public func contain<S: Sequence & SetAlgebra>(_ items: S.Element...) -> Predicate<S> where S.Element: Equatable { return contain(items) } /// A Nimble matcher that succeeds when the actual set contains the expected values. public func contain<S: Sequence & SetAlgebra>(_ items: [S.Element]) -> Predicate<S> where S.Element: Equatable { return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in guard let actual = try actualExpression.evaluate() else { return .fail } let matches = items.allSatisfy { return actual.contains($0) } return PredicateStatus(bool: matches) } } /// A Nimble matcher that succeeds when the actual string contains the expected substring. public func contain(_ substrings: String...) -> Predicate<String> { return contain(substrings) } public func contain(_ substrings: [String]) -> Predicate<String> { return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in guard let actual = try actualExpression.evaluate() else { return .fail } let matches = substrings.allSatisfy { let range = actual.range(of: $0) return range != nil && !range!.isEmpty } return PredicateStatus(bool: matches) } } #if canImport(Foundation) /// A Nimble matcher that succeeds when the actual string contains the expected substring. public func contain(_ substrings: NSString...) -> Predicate<NSString> { return contain(substrings) } public func contain(_ substrings: [NSString]) -> Predicate<NSString> { return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in guard let actual = try actualExpression.evaluate() else { return .fail } let matches = substrings.allSatisfy { actual.range(of: $0.description).length != 0 } return PredicateStatus(bool: matches) } } #endif /// A Nimble matcher that succeeds when the actual collection contains the expected object. public func contain(_ items: Any?...) -> Predicate<NMBContainer> { return contain(items) } public func contain(_ items: [Any?]) -> Predicate<NMBContainer> { return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in guard let actual = try actualExpression.evaluate() else { return .fail } let matches = items.allSatisfy { item in return item.map { actual.contains($0) } ?? false } return PredicateStatus(bool: matches) } } #if canImport(Darwin) extension NMBPredicate { @objc public class func containMatcher(_ expected: [NSObject]) -> NMBPredicate { return NMBPredicate { actualExpression in let location = actualExpression.location let actualValue = try actualExpression.evaluate() if let value = actualValue as? NMBContainer { let expr = Expression(expression: ({ value as NMBContainer }), location: location) // A straightforward cast on the array causes this to crash, so we have to cast the individual items let expectedOptionals: [Any?] = expected.map({ $0 as Any? }) return try contain(expectedOptionals).satisfies(expr).toObjectiveC() } else if let value = actualValue as? NSString { let expr = Expression(expression: ({ value as String }), location: location) // swiftlint:disable:next force_cast return try contain(expected as! [String]).satisfies(expr).toObjectiveC() } let message: ExpectationMessage if actualValue != nil { message = ExpectationMessage.expectedActualValueTo( "contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)" ) } else { message = ExpectationMessage .expectedActualValueTo("contain <\(arrayAsString(expected))>") .appendedBeNilHint() } return NMBPredicateResult(status: .fail, message: message.toObjectiveC()) } } } #endif
apache-2.0
1ecfe7280aa74f3a1aa4b57b43a91879
40.927007
121
0.662953
4.888511
false
false
false
false
NeilNie/Done-
Pods/Eureka/Source/Rows/Controllers/MultipleSelectorViewController.swift
1
6577
// MultipleSelectorViewController.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Selector Controller that enables multiple selection open class _MultipleSelectorViewController<Row: SelectableRowType, OptionsRow: OptionsProviderRow> : FormViewController, TypedRowControllerType where Row: BaseRow, Row.Cell.Value == OptionsRow.OptionsProviderType.Option, OptionsRow.OptionsProviderType.Option: Hashable { /// The row that pushed or presented this controller public var row: RowOf<Set<OptionsRow.OptionsProviderType.Option>>! public var selectableRowSetup: ((_ row: Row) -> Void)? public var selectableRowCellSetup: ((_ cell: Row.Cell, _ row: Row) -> Void)? public var selectableRowCellUpdate: ((_ cell: Row.Cell, _ row: Row) -> Void)? /// A closure to be called when the controller disappears. public var onDismissCallback: ((UIViewController) -> Void)? /// A closure that should return key for particular row value. /// This key is later used to break options by sections. public var sectionKeyForValue: ((Row.Cell.Value) -> (String))? /// A closure that returns header title for a section for particular key. /// By default returns the key itself. public var sectionHeaderTitleForKey: ((String) -> String?)? = { $0 } /// A closure that returns footer title for a section for particular key. public var sectionFooterTitleForKey: ((String) -> String?)? public var optionsProviderRow: OptionsRow { return row as! OptionsRow } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience public init(_ callback: ((UIViewController) -> Void)?) { self.init(nibName: nil, bundle: nil) onDismissCallback = callback } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func viewDidLoad() { super.viewDidLoad() setupForm() } open func setupForm() { optionsProviderRow.optionsProvider?.options(for: self) { [weak self] (options: [OptionsRow.OptionsProviderType.Option]?) in guard let strongSelf = self, let options = options else { return } strongSelf.optionsProviderRow.cachedOptionsData = options strongSelf.setupForm(with: options) } } open func setupForm(with options: [OptionsRow.OptionsProviderType.Option]) { if let optionsBySections = optionsBySections(with: options) { for (sectionKey, options) in optionsBySections { form +++ section(with: options, header: sectionHeaderTitleForKey?(sectionKey), footer: sectionFooterTitleForKey?(sectionKey)) } } else { form +++ section(with: options, header: row.title, footer: nil) } } open func optionsBySections(with options: [OptionsRow.OptionsProviderType.Option]) -> [(String, [Row.Cell.Value])]? { guard let sectionKeyForValue = sectionKeyForValue else { return nil } let sections = options.reduce([:]) { (reduced, option) -> [String: [Row.Cell.Value]] in var reduced = reduced let key = sectionKeyForValue(option) var items = reduced[key] ?? [] items.append(option) reduced[key] = items return reduced } return sections.sorted(by: { (lhs, rhs) in lhs.0 < rhs.0 }) } func section(with options: [OptionsRow.OptionsProviderType.Option], header: String?, footer: String?) -> SelectableSection<Row> { let section = SelectableSection<Row>(header: header ?? "", footer: footer ?? "", selectionType: .multipleSelection) { section in section.onSelectSelectableRow = { [weak self] _, selectableRow in var newValue: Set<OptionsRow.OptionsProviderType.Option> = self?.row.value ?? [] if let selectableValue = selectableRow.value { newValue.insert(selectableValue) } else { newValue.remove(selectableRow.selectableValue!) } self?.row.value = newValue } } for option in options { section <<< Row.init { lrow in lrow.title = String(describing: option) lrow.selectableValue = option lrow.value = self.row.value?.contains(option) ?? false ? option : nil self.selectableRowSetup?(lrow) }.cellSetup { [weak self] cell, row in self?.selectableRowCellSetup?(cell, row) }.cellUpdate { [weak self] cell, row in self?.selectableRowCellUpdate?(cell, row) } } return section } } open class MultipleSelectorViewController<OptionsRow: OptionsProviderRow>: _MultipleSelectorViewController<ListCheckRow<OptionsRow.OptionsProviderType.Option>, OptionsRow> where OptionsRow.OptionsProviderType.Option: Hashable{ override public init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
apache-2.0
02bd83509e1976e45f24fc4879fc5f3c
43.439189
270
0.660484
4.904549
false
false
false
false
rithms/lolesports-kit
Data/FantasyStatsPlayerGame.swift
1
1370
// // FantasyStatsPlayerGame.swift // eSportsKitProject // // Created by Taylor Caldwell on 7/15/15. // Copyright (c) 2015 Rithms. All rights reserved. // import Foundation struct FantasyStatsPlayerGame { var dateTime: NSDate? // Timestamp of when this game was played var matchId: Int? // Match ID var players: [PlayerFantasyStats]? init(data: [String : AnyObject]) { for (key, value) in data { switch(key) { case LolEsportsClient.JSONKeys.DateTime: let date = data[key] as? String dateTime = date?.toNSDate() case LolEsportsClient.JSONKeys.MatchId: let id = data[LolEsportsClient.JSONKeys.MatchId] as? String matchId = id?.toInt() default: if players == nil { players = [PlayerFantasyStats]() } players?.append(PlayerFantasyStats(data: data[key]!)) } } } static func playerStatsFromResults(results: [String : AnyObject]) -> [FantasyStatsPlayerGame] { var playerStats = [FantasyStatsPlayerGame]() for (key, value) in results { playerStats.append(FantasyStatsPlayerGame(data: value as! [String : AnyObject])) } return playerStats } }
mit
038a889394e3e9d3f34f44bb869c8536
28.804348
99
0.566423
4.267913
false
false
false
false
EventsNetwork/Source
LetsTravel/Tour.swift
1
1793
// // Tour.swift // LetsTravel // // Created by TriNgo on 4/13/16. // Copyright © 2016 TriNgo. All rights reserved. // import UIKit import SwiftyJSON class Tour: NSObject { var tourId: Int? var userId: Int? var startTime: Int? var desc: String? var minCost: Double? var maxCost: Double? var provinceId: Int? var totalDay: Int? var favouriteCount: Int? var imageUrls: [String]? var tourEvents: [TourEvent]? var provinceName:String? override init() { } init(dictionary: NSDictionary) { let json = JSON(dictionary) tourId = Int(json["tour_id"].string!) userId = Int(json["user_id"].string!) startTime = Int(json["start_time"].string!) desc = json["description"].string minCost = Double(json["min_cost"].string!) maxCost = Double(json["max_cost"].string!) provinceId = Int(json["province_id"].string!) totalDay = Int(json["total_date"].string!) favouriteCount = Int(json["favourite_count"].string!) let imageUrlString = dictionary["image_urls"] as? String imageUrls = imageUrlString?.characters.split(",").map(String.init) if dictionary["event_day"] != nil { let eventDayDictionary = dictionary["event_day"] as! [[NSDictionary]] tourEvents = TourEvent.getTourEvents(eventDayDictionary) } provinceName = json["province_name"].string! } class func getTours(dictionaries: [NSDictionary]) -> [Tour]{ var tours = [Tour]() for dictionary in dictionaries { let tour = Tour(dictionary: dictionary) tours.append(tour) } return tours } }
apache-2.0
1c2eeb3e94b192ac78ac9f93cc995ace
26.569231
81
0.580915
4.206573
false
false
false
false
moozzyk/SignalR-Client-Swift
Examples/ConnectionSample/AppDelegate.swift
1
3050
// // AppDelegate.swift // ConnectionSample // // Created by Pawel Kadluczka on 2/26/17. // Copyright © 2017 Pawel Kadluczka. All rights reserved. // import Cocoa import SignalRClient @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var openBtn: NSButton! @IBOutlet weak var sendBtn: NSButton! @IBOutlet weak var closeBtn: NSButton! @IBOutlet weak var urlTextField: NSTextField! @IBOutlet weak var msgTextField: NSTextField! @IBOutlet weak var logTextField: NSTextField! @IBOutlet weak var historyTextField: NSTextField! var echoConnection: Connection? var echoConnectionDelegate: ConnectionDelegate? func applicationDidFinishLaunching(_ aNotification: Notification) { toggleSend(isEnabled: false) appendLog(string: "Log") } func applicationWillTerminate(_ aNotification: Notification) { echoConnection?.stop(stopError: nil) } @IBAction func btnOpen(sender: AnyObject) { let url = URL(string: urlTextField.stringValue)! let options = HttpConnectionOptions() options.callbackQueue = DispatchQueue.main echoConnection = HttpConnection(url: url, options: options) echoConnectionDelegate = EchoConnectionDelegate(app: self) echoConnection!.delegate = echoConnectionDelegate echoConnection!.start() } @IBAction func btnSend(sender: AnyObject) { appendLog(string: "Sending: " + msgTextField.stringValue) echoConnection?.send(data: msgTextField.stringValue.data(using: .utf8)!) { error in if let e = error { print(e) } } msgTextField.stringValue = "" } @IBAction func btnClose(sender: AnyObject) { echoConnection?.stop(stopError: nil) } func toggleSend(isEnabled: Bool) { urlTextField.isEnabled = !isEnabled openBtn.isEnabled = !isEnabled msgTextField.isEnabled = isEnabled sendBtn.isEnabled = isEnabled closeBtn.isEnabled = isEnabled } func appendLog(string: String) { logTextField.stringValue += string + "\n" } } class EchoConnectionDelegate: ConnectionDelegate { weak var app: AppDelegate? init(app: AppDelegate) { self.app = app } func connectionDidOpen(connection: Connection) { app?.appendLog(string: "Connection started") app?.toggleSend(isEnabled: true) } func connectionDidFailToOpen(error: Error) { app?.appendLog(string: "Error") } func connectionDidReceiveData(connection: Connection, data: Data) { app?.appendLog(string: "Received: " + String(data: data, encoding: .utf8)!) } func connectionDidClose(error: Error?) { app?.appendLog(string: "Connection stopped") if error != nil { print(error.debugDescription) app?.appendLog(string: error.debugDescription) } app?.toggleSend(isEnabled: false) } }
mit
f08320b55d2264c95a111ec270780958
27.764151
91
0.665464
4.697997
false
false
false
false
mshhmzh/firefox-ios
Utils/Functions.swift
2
5787
/* 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/. */ // Pipelining. infix operator |> { associativity left } public func |> <T, U>(x: T, f: T -> U) -> U { return f(x) } // Basic currying. public func curry<A, B>(f: (A) -> B) -> A -> B { return { a in return f(a) } } public func curry<A, B, C>(f: (A, B) -> C) -> A -> B -> C { return { a in return { b in return f(a, b) } } } public func curry<A, B, C, D>(f: (A, B, C) -> D) -> A -> B -> C -> D { return { a in return { b in return { c in return f(a, b, c) } } } } public func curry<A, B, C, D, E>(f: (A, B, C, D) -> E) -> (A, B, C) -> D -> E { return { (a, b, c) in return { d in return f(a, b, c, d) } } } // Function composition. infix operator • {} public func •<T, U, V>(f: T -> U, g: U -> V) -> T -> V { return { t in return g(f(t)) } } public func •<T, V>(f: T -> (), g: () -> V) -> T -> V { return { t in f(t) return g() } } public func •<V>(f: () -> (), g: () -> V) -> () -> V { return { f() return g() } } // Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse. // This is enough to catch arrays, which Swift will delegate to element-==. public func optArrayEqual<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool { switch (lhs, rhs) { case (.None, .None): return true case (.None, _): return false case (_, .None): return false default: // This delegates to Swift's own array '==', which calls T's == on each element. return lhs! == rhs! } } /** * Given an array, return an array of slices of size `by` (possibly excepting the last slice). * * If `by` is longer than the input, returns a single chunk. * If `by` is less than 1, acts as if `by` is 1. * If the length of the array isn't a multiple of `by`, the final slice will * be smaller than `by`, but never empty. * * If the input array is empty, returns an empty array. */ public func chunk<T>(arr: [T], by: Int) -> [ArraySlice<T>] { let count = arr.count let step = max(1, by) // Handle out-of-range 'by'. let s = 0.stride(to: count, by: step) return s.map { arr[$0..<$0.advancedBy(step, limit: count)] } } public extension SequenceType { // [T] -> (T -> K) -> [K: [T]] // As opposed to `groupWith` (to follow Haskell's naming), which would be // [T] -> (T -> K) -> [[T]] func groupBy<Key, Value>(selector: Self.Generator.Element -> Key, transformer: Self.Generator.Element -> Value) -> [Key: [Value]] { var acc: [Key: [Value]] = [:] for x in self { let k = selector(x) var a = acc[k] ?? [] a.append(transformer(x)) acc[k] = a } return acc } func zip<S: SequenceType>(elems: S) -> [(Self.Generator.Element, S.Generator.Element)] { var rights = elems.generate() return self.flatMap { lhs in guard let rhs = rights.next() else { return nil } return (lhs, rhs) } } } public func optDictionaryEqual<K: Equatable, V: Equatable>(lhs: [K: V]?, rhs: [K: V]?) -> Bool { switch (lhs, rhs) { case (.None, .None): return true case (.None, _): return false case (_, .None): return false default: return lhs! == rhs! } } /** * Return members of `a` that aren't nil, changing the type of the sequence accordingly. */ public func optFilter<T>(a: [T?]) -> [T] { return a.flatMap { $0 } } /** * Return a new map with only key-value pairs that have a non-nil value. */ public func optFilter<K, V>(source: [K: V?]) -> [K: V] { var m = [K: V]() for (k, v) in source { if let v = v { m[k] = v } } return m } /** * Map a function over the values of a map. */ public func mapValues<K, T, U>(source: [K: T], f: (T -> U)) -> [K: U] { var m = [K: U]() for (k, v) in source { m[k] = f(v) } return m } public func findOneValue<K, V>(map: [K: V], f: V -> Bool) -> V? { for v in map.values { if f(v) { return v } } return nil } /** * Take a JSON array, returning the String elements as an array. * It's usually convenient for this to accept an optional. */ public func jsonsToStrings(arr: [JSON]?) -> [String]? { if let arr = arr { return optFilter(arr.map { j in return j.asString }) } return nil } // Encapsulate a callback in a way that we can use it with NSTimer. private class Callback { private let handler:()->() init(handler:()->()) { self.handler = handler } @objc func go() { handler() } } /** * Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call * Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires. **/ public func debounce(delay:NSTimeInterval, action:()->()) -> ()->() { let callback = Callback(handler: action) var timer: NSTimer? return { // If calling again, invalidate the last timer. if let timer = timer { timer.invalidate() } timer = NSTimer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode) } }
mpl-2.0
b40b71329a54be52ab4600f69cdba205
24.914798
135
0.531407
3.365754
false
false
false
false
rechsteiner/Parchment
Parchment/Classes/PagingFiniteDataSource.swift
1
1358
import Foundation import UIKit class PagingFiniteDataSource: PagingViewControllerInfiniteDataSource { var items: [PagingItem] = [] var viewControllerForIndex: ((Int) -> UIViewController?)? func pagingViewController(_: PagingViewController, viewControllerFor pagingItem: PagingItem) -> UIViewController { guard let index = items.firstIndex(where: { $0.isEqual(to: pagingItem) }) else { fatalError("pagingViewController:viewControllerFor: PagingItem does not exist") } guard let viewController = viewControllerForIndex?(index) else { fatalError("pagingViewController:viewControllerFor: No view controller exist for PagingItem") } return viewController } func pagingViewController(_: PagingViewController, itemBefore pagingItem: PagingItem) -> PagingItem? { guard let index = items.firstIndex(where: { $0.isEqual(to: pagingItem) }) else { return nil } if index > 0 { return items[index - 1] } return nil } func pagingViewController(_: PagingViewController, itemAfter pagingItem: PagingItem) -> PagingItem? { guard let index = items.firstIndex(where: { $0.isEqual(to: pagingItem) }) else { return nil } if index < items.count - 1 { return items[index + 1] } return nil } }
mit
07a1f0c8f43cf53aa0dec4867a189a90
38.941176
118
0.66863
5.163498
false
false
false
false
mojio/mojio-ios-sdk
MojioSDK/Models/VinDetails/ServiceBulletin.swift
1
1080
// // ServiceBulletin.swift // MojioSDK // // Created by Ashish Agarwal on 2016-02-26. // Copyright © 2016 Mojio. All rights reserved. // import UIKit import ObjectMapper public class ServiceBulletin: Mappable { public dynamic var ItemNumber : String? = nil public dynamic var BulletinNumber : String? = nil public dynamic var ReplacementBulletinNumber : String? = nil public dynamic var DateAdded : String? = nil public dynamic var Component : String? = nil public dynamic var BulletinDate : String? = nil public dynamic var Summary : String? = nil public required convenience init?(_ map: Map) { self.init(); } public required init() { } public func mapping(map: Map) { ItemNumber <- map["ItemNumber"] BulletinNumber <- map["BulletinNumber"] ReplacementBulletinNumber <- map["ReplacementBulletinNumber"] DateAdded <- map["DateAdded"] Component <- map["Component"] BulletinDate <- map["BulletinDate"] Summary <- map["Summary"] } }
mit
1978a9c7adf0aa41d9526b97d20a45f8
26.666667
69
0.645042
4.458678
false
false
false
false
dhanvi/firefox-ios
Providers/Profile.swift
1
30518
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Account import ReadingList import Shared import Storage import Sync import XCGLogger private let log = Logger.syncLogger public let ProfileDidStartSyncingNotification = "ProfileDidStartSyncingNotification" public let ProfileDidFinishSyncingNotification = "ProfileDidFinishSyncingNotification" public protocol SyncManager { var isSyncing: Bool { get } func syncClients() -> SyncResult func syncClientsThenTabs() -> SyncResult func syncHistory() -> SyncResult func syncLogins() -> SyncResult func syncEverything() -> Success // The simplest possible approach. func beginTimedSyncs() func endTimedSyncs() func applicationDidEnterBackground() func applicationDidBecomeActive() func onRemovedAccount(account: FirefoxAccount?) -> Success func onAddedAccount() -> Success } typealias EngineIdentifier = String typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult class ProfileFileAccessor: FileAccessor { convenience init(profile: Profile) { self.init(localName: profile.localName()) } init(localName: String) { let profileDirName = "profile.\(localName)" // Bug 1147262: First option is for device, second is for simulator. var rootPath: NSString if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path { rootPath = path as NSString } else { log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.") rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]) as NSString } super.init(rootPath: rootPath.stringByAppendingPathComponent(profileDirName)) } } class CommandStoringSyncDelegate: SyncDelegate { let profile: Profile init() { profile = BrowserProfile(localName: "profile", app: nil) } func displaySentTabForURL(URL: NSURL, title: String) { let item = ShareItem(url: URL.absoluteString, title: title, favicon: nil) self.profile.queue.addToQueue(item) } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ let TabSendURLKey = "TabSendURL" let TabSendTitleKey = "TabSendTitle" let TabSendCategory = "TabSendCategory" enum SentTabAction: String { case View = "TabSendViewAction" case Bookmark = "TabSendBookmarkAction" case ReadingList = "TabSendReadingListAction" } class BrowserProfileSyncDelegate: SyncDelegate { let app: UIApplication init(app: UIApplication) { self.app = app } // SyncDelegate func displaySentTabForURL(URL: NSURL, title: String) { // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them if let currentSettings = app.currentUserNotificationSettings() { if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 { log.info("Displaying notification for URL \(URL.absoluteString)") let notification = UILocalNotification() notification.fireDate = NSDate() notification.timeZone = NSTimeZone.defaultTimeZone() notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString) notification.userInfo = [TabSendURLKey: URL.absoluteString, TabSendTitleKey: title] notification.alertAction = nil notification.category = TabSendCategory app.presentLocalNotificationNow(notification) } } } } /** * A Profile manages access to the user's data. */ protocol Profile: class { var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> { get } // var favicons: Favicons { get } var prefs: Prefs { get } var queue: TabQueue { get } var searchEngines: SearchEngines { get } var files: FileAccessor { get } var history: protocol<BrowserHistory, SyncableHistory> { get } var favicons: Favicons { get } var readingList: ReadingListService? { get } var logins: protocol<BrowserLogins, SyncableLogins> { get } func shutdown() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String // URLs and account configuration. var accountConfiguration: FirefoxAccountConfiguration { get } // Do we have an account at all? func hasAccount() -> Bool // Do we have an account that (as far as we know) is in a syncable state? func hasSyncableAccount() -> Bool func getAccount() -> FirefoxAccount? func removeAccount() func setAccount(account: FirefoxAccount) func getClients() -> Deferred<Maybe<[RemoteClient]>> func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) var syncManager: SyncManager { get } } public class BrowserProfile: Profile { private let name: String internal let files: FileAccessor weak private var app: UIApplication? init(localName: String, app: UIApplication?) { self.name = localName self.files = ProfileFileAccessor(localName: localName) self.app = app let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: NotificationOnLocationChange, object: nil) if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() { KeychainWrapper.serviceName = baseBundleIdentifier } else { log.error("Unable to get the base bundle identifier. Keychain data will not be shared.") } // If the profile dir doesn't exist yet, this is first run (for this profile). if !files.exists("") { log.info("New profile. Removing old account data.") removeAccount() prefs.clearAll() } } // Extensions don't have a UIApplication. convenience init(localName: String) { self.init(localName: localName, app: nil) } func shutdown() { if self.dbCreated { db.close() } if self.loginsDBCreated { loginsDB.close() } } @objc func onLocationChange(notification: NSNotification) { if let v = notification.userInfo!["visitType"] as? Int, let visitType = VisitType(rawValue: v), let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url), let title = notification.userInfo!["title"] as? NSString { // Only record local vists if the change notification originated from a non-private tab if !(notification.userInfo!["isPrivate"] as? Bool ?? false) { // We don't record a visit if no type was specified -- that means "ignore me". let site = Site(url: url.absoluteString, title: title as String) let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType) log.debug("Recording visit for \(url) with type \(v).") history.addLocalVisit(visit) } } else { let url = notification.userInfo!["url"] as? NSURL log.debug("Ignoring navigation for \(url).") } } deinit { self.syncManager.endTimedSyncs() NSNotificationCenter.defaultCenter().removeObserver(self) } func localName() -> String { return name } lazy var queue: TabQueue = { withExtendedLifetime(self.history) { return SQLiteQueue(db: self.db) } }() private var dbCreated = false var db: BrowserDB { struct Singleton { static var token: dispatch_once_t = 0 static var instance: BrowserDB! } dispatch_once(&Singleton.token) { Singleton.instance = BrowserDB(filename: "browser.db", files: self.files) self.dbCreated = true } return Singleton.instance } /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. * * Any other class that needs to access any one of these should ensure * that this is initialized first. */ private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = { return SQLiteHistory(db: self.db)! }() var favicons: Favicons { return self.places } var history: protocol<BrowserHistory, SyncableHistory> { return self.places } lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = { // Make sure the rest of our tables are initialized before we try to read them! // This expression is for side-effects only. withExtendedLifetime(self.places) { return MergedSQLiteBookmarks(db: self.db) } }() lazy var mirrorBookmarks: BookmarkMirrorStorage = { // Yeah, this is lazy. Sorry. return self.bookmarks as! MergedSQLiteBookmarks }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs) }() func makePrefs() -> Prefs { return NSUserDefaultsPrefs(prefix: self.localName()) } lazy var prefs: Prefs = { return self.makePrefs() }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath as String) }() private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var syncManager: SyncManager = { return BrowserSyncManager(profile: self) }() private func getSyncDelegate() -> SyncDelegate { if let app = self.app { return BrowserProfileSyncDelegate(app: app) } return CommandStoringSyncDelegate() } public func getClients() -> Deferred<Maybe<[RemoteClient]>> { return self.syncManager.syncClients() >>> { self.remoteClientsAndTabs.getClients() } } public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.syncManager.syncClientsThenTabs() >>> { self.remoteClientsAndTabs.getClientsAndTabs() } } public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> { return self.remoteClientsAndTabs.getClientsAndTabs() } func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) { let commands = items.map { item in SyncCommand.fromShareItem(item, withAction: "displayURI") } self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() } } lazy var logins: protocol<BrowserLogins, SyncableLogins> = { return SQLiteLogins(db: self.loginsDB) }() private lazy var loginsKey: String? = { let key = "sqlcipher.key.logins.db" if KeychainWrapper.hasValueForKey(key) { return KeychainWrapper.stringForKey(key) } let Length: UInt = 256 let secret = Bytes.generateRandomBytes(Length).base64EncodedString KeychainWrapper.setString(secret, forKey: key) return secret }() private var loginsDBCreated = false private lazy var loginsDB: BrowserDB = { struct Singleton { static var token: dispatch_once_t = 0 static var instance: BrowserDB! } dispatch_once(&Singleton.token) { Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files) self.loginsDBCreated = true } return Singleton.instance }() let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration() private lazy var account: FirefoxAccount? = { if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] { return FirefoxAccount.fromDictionary(dictionary) } return nil }() func hasAccount() -> Bool { return account != nil } func hasSyncableAccount() -> Bool { return account?.actionNeeded == FxAActionNeeded.None } func getAccount() -> FirefoxAccount? { return account } func removeAccount() { let old = self.account prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime) KeychainWrapper.removeObjectForKey(name + ".account") self.account = nil // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) // Trigger cleanup. Pass in the account in case we want to try to remove // client-specific data from the server. self.syncManager.onRemovedAccount(old) // deregister for remote notifications app?.unregisterForRemoteNotifications() } func setAccount(account: FirefoxAccount) { KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account") self.account = account // register for notifications for the account registerForNotifications() // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) self.syncManager.onAddedAccount() } func registerForNotifications() { let viewAction = UIMutableUserNotificationAction() viewAction.identifier = SentTabAction.View.rawValue viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") viewAction.activationMode = UIUserNotificationActivationMode.Foreground viewAction.destructive = false viewAction.authenticationRequired = false let bookmarkAction = UIMutableUserNotificationAction() bookmarkAction.identifier = SentTabAction.Bookmark.rawValue bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground bookmarkAction.destructive = false bookmarkAction.authenticationRequired = false let readingListAction = UIMutableUserNotificationAction() readingListAction.identifier = SentTabAction.ReadingList.rawValue readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") readingListAction.activationMode = UIUserNotificationActivationMode.Foreground readingListAction.destructive = false readingListAction.authenticationRequired = false let sentTabsCategory = UIMutableUserNotificationCategory() sentTabsCategory.identifier = TabSendCategory sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default) sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal) app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory])) app?.registerForRemoteNotifications() } // Extends NSObject so we can use timers. class BrowserSyncManager: NSObject, SyncManager { unowned private let profile: BrowserProfile let FifteenMinutes = NSTimeInterval(60 * 15) let OneMinute = NSTimeInterval(60) private var syncTimer: NSTimer? = nil private var backgrounded: Bool = true func applicationDidEnterBackground() { self.backgrounded = true self.endTimedSyncs() } func applicationDidBecomeActive() { self.backgrounded = false self.beginTimedSyncs() } /** * Locking is managed by withSyncInputs. Make sure you take and release these * whenever you do anything Sync-ey. */ var syncLock = OSSpinLock() { didSet { let notification = syncLock == 0 ? ProfileDidFinishSyncingNotification : ProfileDidStartSyncingNotification NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: notification, object: nil)) } } // According to the OSAtomic header documentation, the convention for an unlocked lock is a zero value // and a locked lock is a non-zero value var isSyncing: Bool { return syncLock != 0 } private func beginSyncing() -> Bool { return OSSpinLockTry(&syncLock) } private func endSyncing() { OSSpinLockUnlock(&syncLock) } init(profile: BrowserProfile) { self.profile = profile super.init() let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil) center.addObserver(self, selector: "onFinishSyncing:", name: ProfileDidFinishSyncingNotification, object: nil) } deinit { // Remove 'em all. let center = NSNotificationCenter.defaultCenter() center.removeObserver(self, name: NotificationDataLoginDidChange, object: nil) center.removeObserver(self, name: ProfileDidFinishSyncingNotification, object: nil) } // Simple in-memory rate limiting. var lastTriggeredLoginSync: Timestamp = 0 @objc func onLoginDidChange(notification: NSNotification) { log.debug("Login did change.") if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds { lastTriggeredLoginSync = NSDate.now() // Give it a few seconds. let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered) // Trigger on the main queue. The bulk of the sync work runs in the background. dispatch_after(when, dispatch_get_main_queue()) { self.syncLogins() } } } @objc func onFinishSyncing(notification: NSNotification) { profile.prefs.setTimestamp(NSDate.now(), forKey: PrefsKeys.KeyLastSyncFinishTime) } var prefsForSync: Prefs { return self.profile.prefs.branch("sync") } func onAddedAccount() -> Success { return self.syncEverything() } func onRemovedAccount(account: FirefoxAccount?) -> Success { let h: SyncableHistory = self.profile.history let flagHistory = { h.onRemovedAccount() } let clearTabs = { self.profile.remoteClientsAndTabs.onRemovedAccount() } // Run these in order, because they both write to the same DB! return accumulate([flagHistory, clearTabs]) >>> { // Clear prefs after we're done clearing everything else -- just in case // one of them needs the prefs and we race. Clear regardless of success // or failure. // This will remove keys from the Keychain if they exist, as well // as wiping the Sync prefs. SyncStateMachine.clearStateFromPrefs(self.prefsForSync) return succeed() } } private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer { return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true) } func beginTimedSyncs() { if self.syncTimer != nil { log.debug("Already running sync timer.") return } let interval = FifteenMinutes let selector = Selector("syncOnTimer") log.debug("Starting sync timer.") self.syncTimer = repeatingTimerAtInterval(interval, selector: selector) } /** * The caller is responsible for calling this on the same thread on which it called * beginTimedSyncs. */ func endTimedSyncs() { if let t = self.syncTimer { log.debug("Stopping sync timer.") self.syncTimer = nil t.invalidate() } } private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing clients to storage.") let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs) return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info) } private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { let storage = self.profile.remoteClientsAndTabs let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs) return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info) } private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing history to storage.") let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs) return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info) } private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing logins to storage.") let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs) return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info) } private func mirrorBookmarksWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { // Temporarily turned off. return deferMaybe(SyncStatus.NotStarted(SyncNotStartedReason.EngineRemotelyNotEnabled(collection: "bookmarks"))) /* log.debug("Mirroring server bookmarks to storage.") let bookmarksMirrorer = ready.synchronizer(MirroringBookmarksSynchronizer.self, delegate: delegate, prefs: prefs) return bookmarksMirrorer.mirrorBookmarksToStorage(self.profile.mirrorBookmarks, withServer: ready.client, info: ready.info, greenLight: self.greenLight()) */ } /** * Returns nil if there's no account. */ private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>>? { if let account = profile.account { if !beginSyncing() { log.info("Not syncing \(label); already syncing something.") return deferMaybe(AlreadySyncingError()) } if let label = label { log.info("Syncing \(label).") } let authState = account.syncAuthState let syncPrefs = profile.prefs.branch("sync") let readyDeferred = SyncStateMachine.toReady(authState, prefs: syncPrefs) let delegate = profile.getSyncDelegate() let go = readyDeferred >>== { ready in function(delegate, syncPrefs, ready) } // Always unlock when we're done. go.upon({ res in self.endSyncing() }) return go } log.warning("No account; can't sync.") return nil } /** * Runs the single provided synchronization function and returns its status. */ private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult { return self.withSyncInputs(label, function: function) ?? deferMaybe(.NotStarted(.NoAccount)) } /** * Runs each of the provided synchronization functions with the same inputs. * Returns an array of IDs and SyncStatuses the same length as the input. */ private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> { typealias Pair = (EngineIdentifier, SyncStatus) let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[Pair]>> = { delegate, syncPrefs, ready in let thunks = synchronizers.map { (i, f) in return { () -> Deferred<Maybe<Pair>> in log.debug("Syncing \(i)…") return f(delegate, syncPrefs, ready) >>== { deferMaybe((i, $0)) } } } return accumulate(thunks) } return self.withSyncInputs(nil, function: combined) ?? deferMaybe(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) }) } func syncEverything() -> Success { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate), ("logins", self.syncLoginsWithDelegate), ("bookmarks", self.mirrorBookmarksWithDelegate), ("history", self.syncHistoryWithDelegate) ) >>> succeed } @objc func syncOnTimer() { log.debug("Running timed logins sync.") // Note that we use .upon here rather than chaining with >>> precisely // to allow us to sync subsequent engines regardless of earlier failures. // We don't fork them in parallel because we want to limit perf impact // due to background syncs, and because we're cautious about correctness. self.syncLogins().upon { result in if let success = result.successValue { log.debug("Timed logins sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed logins sync failed. Reason: \(reason).") } log.debug("Running timed history sync.") self.syncHistory().upon { result in if let success = result.successValue { log.debug("Timed history sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed history sync failed. Reason: \(reason).") } } } } func syncClients() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("clients", function: syncClientsWithDelegate) } func syncClientsThenTabs() -> SyncResult { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate) ) >>== { statuses in let tabsStatus = statuses[1].1 return deferMaybe(tabsStatus) } } func syncLogins() -> SyncResult { return self.sync("logins", function: syncLoginsWithDelegate) } func syncHistory() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("history", function: syncHistoryWithDelegate) } func mirrorBookmarks() -> SyncResult { return self.sync("bookmarks", function: mirrorBookmarksWithDelegate) } /** * Return a thunk that continues to return true so long as an ongoing sync * should continue. */ func greenLight() -> () -> Bool { let start = NSDate.now() // Give it one minute to run before we stop. let stopBy = start + OneMinuteInMilliseconds log.debug("Checking green light. Backgrounded: \(self.backgrounded).") return { !self.backgrounded && NSDate.now() < stopBy && self.profile.hasSyncableAccount() } } } } class AlreadySyncingError: MaybeErrorType { var description: String { return "Already syncing." } }
mpl-2.0
f622e1700615b41437855f666f2450e3
38.123077
238
0.638681
5.321011
false
false
false
false
hhsolar/MemoryMaster-iOS
MemoryMaster/Utility/UIImage+Extension.swift
1
8473
// // UIImage+Extension.swift // MemoryMaster // // Created by apple on 8/10/2017. // Copyright © 2017 greatwall. All rights reserved. // import Foundation import UIKit import Photos extension UIImage { class func imageWithColor(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } class func scaleImage(_ image: UIImage, to scaleSize: CGFloat) -> UIImage? { UIGraphicsBeginImageContext(CGSize(width: image.size.width * scaleSize, height: image.size.height * scaleSize)) image.draw(in: CGRect(x: 0, y: 0, width: image.size.width * scaleSize, height: image.size.height * scaleSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } class func reSizeImage(_ image: UIImage, to size: CGSize) -> UIImage? { UIGraphicsBeginImageContext(CGSize(width: size.width, height: size.height)) image.draw(in: CGRect(origin: CGPoint.zero, size: size)) let reSizeImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return reSizeImage } // make the photo to fit the UITextView size class func scaleImageToFitTextView(_ image: UIImage, fit textViewWidth: CGFloat) -> UIImage? { if image.size.width <= textViewWidth { return image } let size = CGSize(width: textViewWidth, height: textViewWidth * image.size.height / image.size.width) return UIImage.reSizeImage(image, to: size) } // save photo to the library class func saveImageWithPhotoLibrary(image: UIImage) { PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAsset(from: image) }) { (success, error) in if success { print("success = %d, error = %@", success, error!) } } } // async get the photos form library with small size class func async_getLibraryThumbnails(smallImageCallBack: @escaping (_ allSmallImageArray: [UIImage]) -> ()) { let image = UIImage() let concurrentQueue = DispatchQueue(label: "getLibiaryAllImage-queue", attributes: .concurrent) concurrentQueue.async { var smallPhotoArray = [UIImage]() smallPhotoArray.append(contentsOf: UIImage.getImageWithScaleImage(image: image, isOriginalPhoto: false)) DispatchQueue.main.async { smallImageCallBack(smallPhotoArray) } } } // async to get the photos form library with small size and original size at same time class func async_getLibraryPhoto(smallImageCallBack: @escaping (_ allSmallImageArray: [UIImage]) -> (), allOriginalImageCallBack: @escaping (_ allOriginalImageArray: [UIImage]) -> ()) { let image = UIImage() let concurrentQueue = DispatchQueue(label: "getLibiaryAllImage-queue", attributes: .concurrent) concurrentQueue.async { var smallPhotoArray = [UIImage]() smallPhotoArray.append(contentsOf: UIImage.getImageWithScaleImage(image: image, isOriginalPhoto: false)) DispatchQueue.main.async { smallImageCallBack(smallPhotoArray) } } concurrentQueue.async { var allOriginalPhotoArray = [UIImage]() allOriginalPhotoArray.append(contentsOf: UIImage.getImageWithScaleImage(image: image, isOriginalPhoto: true)) DispatchQueue.main.async { allOriginalImageCallBack(allOriginalPhotoArray) } } } // get all the photoes with original size or not class func getImageWithScaleImage(image: UIImage, isOriginalPhoto: Bool) -> [UIImage] { var photoArray = [UIImage]() let assetCollections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil) for i in 0..<assetCollections.count { photoArray.append(contentsOf: image.enumerateAssetsInAssetCollection(assetCollection: assetCollections[i], origial: isOriginalPhoto)) } let cameraRoll = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil).lastObject if let cameraRoll = cameraRoll { photoArray.append(contentsOf: image.enumerateAssetsInAssetCollection(assetCollection: cameraRoll, origial: isOriginalPhoto)) } return photoArray } // get photos form a assection collection func enumerateAssetsInAssetCollection(assetCollection: PHAssetCollection, origial: Bool) -> [UIImage] { var array = [UIImage]() let options = PHImageRequestOptions() options.isSynchronous = true let scale = UIScreen.main.scale let width = (UIScreen.main.bounds.width - 20) / 3 let thumbnailSize = CGSize(width: width * scale, height: width * scale) let assets = PHAsset.fetchAssets(in: assetCollection, options: nil) for i in 0..<assets.count { let size = origial ? CGSize(width: assets[i].pixelWidth, height:assets[i].pixelHeight) : thumbnailSize PHImageManager.default().requestImage(for: assets[i], targetSize: size, contentMode: .default, options: options, resultHandler: { (result, info) in array.append(result!) }) } return array } ////////////////////////// // load a group of thumbnails class func async_getLibraryThumbnails(assets: [PHAsset], smallImageCallBack: @escaping (_ allSmallImageArray: [UIImage]) -> ()) { let concurrentQueue = DispatchQueue(label: "getLibiaryAllImage-queue", attributes: .concurrent) concurrentQueue.async { var smallPhotoArray = [UIImage]() smallPhotoArray.append(contentsOf: getThumbnailsByPhotoAssectArray(assets: assets)) DispatchQueue.main.async { smallImageCallBack(smallPhotoArray) } } } // get thumbnails according to array of photo assects class func getThumbnailsByPhotoAssectArray(assets: [PHAsset]) -> [UIImage] { var array = [UIImage]() let options = PHImageRequestOptions() options.isSynchronous = true let scale = UIScreen.main.scale let width = (UIScreen.main.bounds.width - 20) / 3 let thumbnailSize = CGSize(width: width * scale, height: width * scale) for assets in assets { PHImageManager.default().requestImage(for: assets, targetSize: thumbnailSize, contentMode: .default, options: options, resultHandler: { (result, info) in array.append(result!) }) } return array } // get original size photo according to photo assect class func getOriginalPhoto(asset: PHAsset) -> UIImage { var image = UIImage() let options = PHImageRequestOptions() options.isSynchronous = true let size = CGSize(width: asset.pixelWidth, height:asset.pixelHeight) PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .default, options: options) { (result, info) in image = result! } return image } // get photo asset from all of the albums class func getPhotoAssets() -> [PHAsset] { var array = [PHAsset]() let assetCollections = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil) for i in 0..<assetCollections.count { let assets = PHAsset.fetchAssets(in: assetCollections[i], options: nil) for j in 0..<assets.count { array.append(assets[j]) } } let cameraRoll = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil).lastObject if let cameraRoll = cameraRoll { let rollAssets = PHAsset.fetchAssets(in: cameraRoll, options: nil) for i in 0..<rollAssets.count { array.append(rollAssets[i]) } } return array } }
mit
57f9a725d2bd69967a9ab005570454e0
44.06383
189
0.649433
4.95149
false
false
false
false