blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
625
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
47
| license_type
stringclasses 2
values | repo_name
stringlengths 5
116
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 643
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 80.4k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 16
values | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_language
stringclasses 85
values | src_encoding
stringclasses 7
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 4
6.44M
| extension
stringclasses 17
values | content
stringlengths 4
6.44M
| duplicates
sequencelengths 1
9.02k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b5ad6e9b98b87e684f137f202fb31775540f296b | f3eb12b2ab0267057101d73af38ca7d7f5c424a8 | /Split/Matchers/EqualToMatcher.swift | d2acc72fdf8d5ffcbad9e0c7a62acc4a2e07eb16 | [
"Apache-2.0"
] | permissive | splitio/ios-client | 85645ef71152387255a20ae6f322378eb170312f | dd896627fdd7506775f1da19537f64e52d7f89c3 | refs/heads/master | 2023-08-06T16:57:52.706344 | 2023-07-18T19:51:16 | 2023-07-18T19:51:16 | 103,703,174 | 14 | 20 | NOASSERTION | 2023-08-15T17:27:33 | 2017-09-15T21:32:43 | Swift | UTF-8 | Swift | false | false | 1,351 | swift | //
// EqualToMatcher.swift
// Split
//
// Created by Natalia Stele on 11/23/17.
//
import Foundation
class EqualToMatcher: BaseMatcher, MatcherProtocol {
var data: UnaryNumericMatcherData?
init(data: UnaryNumericMatcherData?, splitClient: DefaultSplitClient? = nil,
negate: Bool? = nil, attribute: String? = nil, type: MatcherType? = nil) {
super.init(negate: negate, attribute: attribute, type: type)
self.data = data
}
func evaluate(values: EvalValues, context: EvalContext?) -> Bool {
guard let matcherData = data, let dataType = matcherData.dataType, let value = matcherData.value else {
return false
}
switch dataType {
case DataType.dateTime:
guard let keyValue = values.matchValue as? TimeInterval else {return false}
let backendTimeInterval = TimeInterval(value/1000)
let attributeTimeInterval = keyValue
let attributeDate = DateTime.zeroOutTime(timestamp: attributeTimeInterval)
let backendDate = DateTime.zeroOutTime(timestamp: backendTimeInterval)
return backendDate == attributeDate
case DataType.number:
guard let keyValue = CastUtils.anyToInt64(value: values.matchValue) else {return false}
return keyValue == value
}
}
}
| [
-1
] |
6b0168470c98c477c8b0e6858a05b3bc82386a0a | 7de83b078409d2b0d7824401167817dfda3e3db1 | /Sources/Service/WebServiceProtocol+Handlers.swift | 8c9e4136fa58ff4549cce48671d278026efdae0e | [
"MIT"
] | permissive | ez-ramzan/NetworkManager | 54f100b40b845c0d3e44b59247ca12bf756a03eb | 5dcc6a777bf65a90f33a878da7f6489b43030594 | refs/heads/master | 2021-02-08T23:14:59.253257 | 2020-09-28T20:40:55 | 2020-09-28T20:40:55 | 244,208,773 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,666 | swift | //
// WebServiceProtocol+Handlers.swift
// Currency Rates
//
// Created by Raman Liulkovich on 9/18/19.
// Copyright © 2019 Raman Liulkovich. All rights reserved.
//
import Foundation
//MARK: - Internal (Handling network response)
internal extension WebServiceProtocol {
func handleNetworkResponse(data: Data?, response: URLResponse?, error: Error?) -> Result<Data, WebError> {
guard error == nil else {
return .failure(WebError(serviceError: .load, systemError: error))
}
guard let httpResponse = response as? HTTPURLResponse else {
return .failure(WebError(serviceError: .httpResponse(.empty), systemError: nil))
}
switch handleHTTPResponse(httpResponse) {
case .success:
guard let data = data else {
return .failure(WebError(serviceError: .emptyData, systemError: nil))
}
return .success(data)
case .failure(let error):
return .failure(WebError(serviceError: .httpResponse(error), systemError: nil))
}
}
}
//MARK: - Private (Handling http response)
private extension WebServiceProtocol {
func handleHTTPResponse(_ httpResponse: HTTPURLResponse) -> Result<Void, HTTPResponseError> {
switch httpResponse.statusCode {
case 200...299:
return .success(())
case 300...399:
return .failure(.redirection)
case 400...499:
return .failure(.client)
case 500...599:
return .failure(.server)
default:
return .failure(.other)
}
}
}
| [
-1
] |
51403c7d471fae9fc3b1c4e2d4c3298a327b37cf | b43568f3cf8d8c20003b04084bd03fee0a3b9c91 | /UI/Source/CollectionViews/CollectionViewModelDataSource.swift | 9dd4dc808657fc8cea95fe969fca92cedbbf5881 | [
"Apache-2.0"
] | permissive | AlexxNica/pilot | 46dc447705f60401efdd6d5d7e134c999df5b177 | 38c43828b1a13aa227dba864b12f85fabe33e751 | refs/heads/master | 2021-01-18T20:08:03.253442 | 2017-04-01T03:08:53 | 2017-04-01T03:08:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 55,220 | swift | import Pilot
import QuartzCore
/// Can be used to provide reuse ids for collection view cells.
public protocol CollectionViewCellReuseIdProvider {
func reuseIdForViewModel(_ viewModel: ViewModel, viewType: View.Type) -> String
}
open class DefaultCollectionViewCellReuseIdProvider: CollectionViewCellReuseIdProvider {
public init() {
}
// MARK: CollectionViewCellReuseIdProvider
/// The default implementation, if a provider isn't specified in the initializer.
open func reuseIdForViewModel(_ viewModel: ViewModel, viewType: View.Type) -> String {
return "\(NSStringFromClass(viewType))-\(type(of: viewModel))"
}
}
private enum CollectionViewState {
/// Don't know exactly what the CollectionView thinks the world looks like until it asks for the section count.
case loading
/// Told CollectionView to performBatchUpdates but it hasn't completed yet.
case animating
/// If the underlying ModelCollection has changed while animating, it must be updated again when the animation
/// completes.
case animatingWithPendingChanges
/// The CollectionView and ModelCollection are in sync with each other.
case synced
}
public final class CurrentCollection: ModelCollection, ProxyingCollectionEventObservable {
// MARK: Init
public init(_ collectionId: ModelCollectionId) {
self.collectionId = collectionId
}
// MARK: ModelCollection
public let collectionId: ModelCollectionId
public fileprivate(set) var state: ModelCollectionState = .notLoaded {
didSet {
observers.notify(.didChangeState(state))
}
}
public var proxiedObservable: GenericObservable<CollectionEvent> { return observers }
private let observers = ObserverList<CollectionEvent>()
// MARK: Private
fileprivate func beginUpdate(_ collection: ModelCollection) -> (CollectionEventUpdates, () -> Void){
let updates = diffEngine.update(collection.sections, debug: false)
let commitState = collection.state
return (updates, {
self.state = commitState
})
}
fileprivate func update(_ collection: ModelCollection) {
let (_, commitCollectionChanges) = beginUpdate(collection)
commitCollectionChanges()
}
private var diffEngine = DiffEngine()
}
/// Data source for collection views which handles all the necessary binding between models -> view models, and view
/// models -> view types. It handles observing the underlying model and handling all required updates to the collection
/// view.
public class CollectionViewModelDataSource: NSObject, ProxyingObservable {
// MARK: Init
public init(
model: ModelCollection,
modelBinder: ViewModelBindingProvider,
viewBinder: ViewBindingProvider,
context: Context,
reuseIdProvider: CollectionViewCellReuseIdProvider
) {
let underlyingCollection = SwitchableModelCollection(collectionId: "CVMDS-Switch", modelCollection: model)
self.underlyingCollection = underlyingCollection
self.currentCollection = CurrentCollection("CVMDS-Current")
self.modelBinder = modelBinder
self.viewBinder = viewBinder
self.context = context
self.reuseIdProvider = reuseIdProvider
self.collectionViewState = .loading
super.init()
self.collectionObserver = self.underlyingCollection.observe { [weak self] event in
self?.handleCollectionEvent(event)
}
registerForNotifications()
}
deinit {
unregisterForNotifications()
}
// MARK: Public
public enum Event {
/// `willUpdateItems` is triggered when the underlying ModelCollection has changed its data, but the
/// updates have not been applied to either the CollectionView or `currentCollection`.
/// While handling this event, `currentCollection` contains the collection's contents before the change.
case willUpdateItems(CollectionEventUpdates)
/// `didUpdateItems` is triggered after the ModelCollection has changed and the CollectionView has
/// finished animating to the new state.
/// Implementation note: In the case of a reload, this event can fire before the CollectionView has updated
/// with the new contents.
case didUpdateItems(CollectionEventUpdates)
}
/// A ModelCollection that provides access to the data as far as the CollectionView knows. If the CollectionView
/// is in the process of being updated, this data might be slightly behind the ModelCollection passed as the constructor.
/// The data in `currentCollection` is updated between the `willUpdateItems` and `didUpdateItems` events.
public let currentCollection: CurrentCollection
/// Underlying model context.
public private(set) var context: Context
/// Associated collection view for this data source. The owner of the `CollectionViewModelDataSource` should set
/// this property after initialization.
public weak var collectionView: PlatformCollectionView? {
willSet {
precondition(newValue != nil)
// TODO(wkiefer) T126138: NestedModelCollectionView binds and unbinds to a data source. We'll have to make
// this class support attach/detatch from a collection view properly.
// precondition(collectionView == nil)
}
}
/// Adds a `ViewModelBindingProvider` for any supplementary views of `kind`. If not set the
/// `DefaultViewModelBindingProvider` is used.
open func setViewModelBinder(_ binder: ViewModelBindingProvider, forSupplementaryElementOfKind kind: String) {
supplementaryViewModelBinderMap[kind] = binder
}
/// Removes any `ViewModelBindingProvider` for supplementary views of `kind`. Once cleared the
/// `DefaultViewModelBindingProvider` will be used.
open func clearViewModelBinder(forSupplementaryElementOfKind kind: String) {
supplementaryViewModelBinderMap[kind] = nil
}
/// Adds a `ViewBindingProvider` to provide views for any supplementary views of the given `kind`.
open func setViewBinder(_ viewBinder: ViewBindingProvider, forSupplementaryElementOfKind kind: String) {
supplementaryViewBinderMap[kind] = viewBinder
}
/// Removes a previously-added `ViewBindingProvider` for supplementary views.
open func clearViewBinderForSupplementaryElementOfKind(_ kind: String) {
supplementaryViewBinderMap[kind] = nil
}
/// Adds an `IndexedModelProvider` for any supplementary views of `kind`. If not set,
/// supplementary views default to the ModelType provided by the ModelCollection for the given
/// index path, or a CollectionZeroItemModel otherwise.
public func setModelProvider(provider: IndexedModelProvider, forSupplementaryElementOfKind kind: String) {
supplementaryModelProviderMap[kind] = provider
}
/// Removes a previously-added `IndexedModelProvider` for supplementary views.
public func clearModelProviderForSupplementaryElementOfKind(kind: String) {
supplementaryModelProviderMap[kind] = nil
}
#if os(iOS)
/// Configures the default background color for all host cells.
open var collectionViewBackgroundColor = UIColor.white
#endif
/// Method to return the preferred layout for a given item. Typically collection view controllers would implement
/// any layout delegate methods that need a size, and call into this to fetch the desired size for an item.
/// TODO(ca): change this to take a ModelPath instead of the heavier IndexPath
open func preferredLayoutForItemAtIndexPath(
_ indexPath: IndexPath,
availableSize: AvailableSize) -> PreferredLayout {
guard let modelItem: Model = currentCollection.atIndexPath(indexPath) else { return .none }
var cachedViewModel = self.cachedViewModel(for: modelItem)
if let layout = cachedViewModel.preferredLayout.layout {
if layout.validCache(forViewModel: cachedViewModel.viewModel) {
return cachedViewModel.preferredLayout
}
}
cachedViewModel.preferredLayout = viewBinder.preferredLayout(
fitting: availableSize,
for: cachedViewModel.viewModel,
context: context)
viewModelCache[modelItem.modelId] = cachedViewModel
return cachedViewModel.preferredLayout
}
/// Same as `preferredLayoutForItemAtIndexPath:availableSize:` but for supplementary view size estimation.
open func preferredLayoutForSupplementaryElementAtIndexPath(
_ indexPath: IndexPath,
kind: String,
availableSize: AvailableSize
) -> PreferredLayout {
guard let supplementaryViewBinder = supplementaryViewBinderMap[kind] else {
fatalError("Request for supplementary kind (\(kind)) that has no registered view binder.")
}
let viewModel = viewModelForSupplementaryElementAtIndexPath(kind, indexPath: indexPath)
// TODO:(wkiefer) Cache supplementary sizes too.
return supplementaryViewBinder.preferredLayout(
fitting: availableSize,
for: viewModel,
context: context)
}
#if os(iOS)
/// Attempts to reload a supplementary element at index path by re-binding the hosted view to the view model
/// Note: This function makes no attempt to determine whether layout needs to be invalidated, so if you're making an
/// update that should trigger the collection view layout being invalidated make sure to do that separately.
open func reloadSupplementaryElementAtIndexPath(_ indexPath: IndexPath, kind: String) {
guard let cv = collectionView else { return }
let supplementaryView = cv.supplementaryView(forElementKind: kind, at: indexPath)
guard let hostView = supplementaryView as? CollectionViewHostResuableView else { return }
guard let hostedView = hostView.hostedView else { return }
let viewModel = viewModelForSupplementaryElementAtIndexPath(kind, indexPath: indexPath)
hostedView.bindToViewModel(viewModel)
hostView.hostedView = hostedView
}
#elseif os(OSX)
/// Attempts to reload a supplementary element at index path by re-binding the hosted view to the view model
/// Note: This function makes no attempt to determine whether layout needs to be invalidated, so if you're making an
/// update that should trigger the collection view layout being invalidated make sure to do that separately.
public func reloadSupplementaryElementAtIndexPath(indexPath: IndexPath, kind: String) {
guard let cv = collectionView else { return }
guard let supplementaryViewBinder = supplementaryViewBinderMap[kind] else { return }
guard let supplementaryView =
cv.supplementaryView(forElementKind: kind, at: indexPath as IndexPath) else { return }
let viewModel = viewModelForSupplementaryElementAtIndexPath(kind, indexPath: indexPath)
let desiredView = supplementaryViewBinder.viewTypeForViewModel(viewModel, context: context)
guard let view = supplementaryView as? View , type(of: view) == desiredView else {
assertWithLog(false, message: "reloadSupplementaryElementAtIndexPath doesn't support changing view types")
return
}
view.bindToViewModel(viewModel)
}
#endif
/// Returns a bound `ViewModel` for the given `indexPath` or nil if the index path is not valid.
open func viewModelAtIndexPath(_ indexPath: IndexPath) -> ViewModel? {
guard let modelItem: Model = currentCollection.atIndexPath(indexPath as IndexPath) else { return nil }
return cachedViewModel(for: modelItem).viewModel
}
/// Block which is invoked anytime a view model will be rebound to a view (typically during updates that don't
/// require a reload of the cell).
open var willRebindViewModel: (ViewModel) -> Void = { _ in }
/// Clears any internally-cached preferred item size calculations. Should typically be called when the size of the
/// collection view will change.
open func clearCachedItemSizes() {
var mutatedViewModelCache: [ModelId: CachedViewModel] = [:]
for (key, cachedViewModel) in viewModelCache {
var updatedCachedViewModel = cachedViewModel
updatedCachedViewModel.preferredLayout = .none
mutatedViewModelCache[key] = updatedCachedViewModel
}
viewModelCache = mutatedViewModelCache
}
/// Allows the caller to swap out the `ModelCollection` for this collection view data source. The CollectionView will
/// animate from the old state to the new state. Useful for asynchronously swapping in ModelCollections after they're
/// loaded.
/// Note: does not update the `Context`
public func updateModel(_ model: ModelCollection) {
underlyingCollection.switchTo(model)
}
/// Same as `updateModel` but allows swapping out the `ModelCollection` and `Context`.
public func updateModel(_ model: ModelCollection, with newContext: Context) {
self.context = newContext
// TODO:(wkiefer) If context has changed - this needs to clear the VM cache and reload data.
updateModel(model)
}
/// Possible styles for any model update animations.
public enum UpdateAnimationStyle {
/// All model update changes are animated.
case always
/// The given update is animated depending on the result of the associated closure.
case conditional((CollectionEventUpdates) -> Bool)
/// No updates are animated, but updates are incremental.
case none
/// No updates are animated, and all updates reload all data.
case noneReloadOnly
}
/// Current update animation style. For details see `UpdateAnimationStyle`.
open var updateAnimationStyle = UpdateAnimationStyle.always
/// Returns whether the given `CollectionEventUpdates` should animate depending on the current value of
/// `updateAnimationStyle` and the contents of the updates.
open func shouldAnimateUpdates(_ updates: CollectionEventUpdates) -> Bool {
switch updateAnimationStyle {
case .always:
return true
case .none, .noneReloadOnly:
return false
case .conditional(let shouldAnimate):
return shouldAnimate(updates)
}
}
/// Provider for collection reuse ids. This is set with a default based on the names of the
/// ViewModel and View, but can be overridden to optimize reuse ids for a collection.
open let reuseIdProvider: CollectionViewCellReuseIdProvider
// MARK: Observable
public var proxiedObservable: GenericObservable<Event> { return observers }
fileprivate let observers = ObserverList<Event>()
// MARK: Private
fileprivate let modelBinder: ViewModelBindingProvider
fileprivate let viewBinder: ViewBindingProvider
/// The collection whose contents are synchronized to this CollectionView.
/// The underlyingCollection's data may be newer than the CollectionView's understanding of the world.
fileprivate let underlyingCollection: SwitchableModelCollection
fileprivate var collectionViewState: CollectionViewState
fileprivate var collectionObserver: Observer?
/// Cache of view models and sizing information.
fileprivate var viewModelCache: [ModelId: CachedViewModel] = [:]
/// Map from supplementary element kind (as `String`) to binding providers for supplementary views.
fileprivate var supplementaryViewBinderMap: [String: ViewBindingProvider] = [:]
/// Map from supplementary element kind (as `String`) to binding providers for supplementary view models.
fileprivate var supplementaryViewModelBinderMap: [String: ViewModelBindingProvider] = [:]
/// Map from supplementary element kind (as `String`) to model provider for supplementary elements.
fileprivate var supplementaryModelProviderMap: [String: IndexedModelProvider] = [:]
fileprivate var notificationTokens: [NSObjectProtocol] = []
fileprivate var inBackground = false
fileprivate func registerForNotifications() {
#if os(iOS)
let nc = NotificationCenter.default
// Note: Rather than observer `UIApplicationWillEnterForegroundNotification`, didBecomeActive is watched instead
// because typically it's better for collection view updates to batch until actually active (instead of multiple
// animations as the application is transitioning).
notificationTokens.append(nc.addObserver(
forName: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil,
queue: OperationQueue.main) { [weak self] _ in
self?.inBackground = false
})
notificationTokens.append(nc.addObserver(
forName: NSNotification.Name.UIApplicationDidEnterBackground,
object: nil,
queue: OperationQueue.main) { [weak self] _ in
self?.inBackground = true
})
#endif // os(iOS)
}
fileprivate func unregisterForNotifications() {
let nc = NotificationCenter.default
notificationTokens.forEach { nc.removeObserver($0) }
notificationTokens.removeAll()
}
fileprivate func modelForSupplementaryIndexPath(_ indexPath: IndexPath, ofKind kind: String) -> Model {
if let provider = supplementaryModelProviderMap[kind] {
// If a provider was set, and that provider provides a model, use it.
if let model = provider.model(for: indexPath, context: context) {
return model
}
} else if let modelItem: Model = currentCollection.atIndexPath(indexPath) {
// If no provider is set but the collection model provides an item at this index path,
// use that one.
return modelItem
}
// If either a provider is set but provides no item, or there is no provider set and the
// collection model does provides no item (such as when a section is empty),
// return a "zero" item.
return CollectionZeroItemModel(indexPath: indexPath)
}
fileprivate func viewModelForSupplementaryElementAtIndexPath(_ kind: String, indexPath: IndexPath) -> ViewModel {
let model = modelForSupplementaryIndexPath(indexPath, ofKind: kind)
if let bindingProvider = supplementaryViewModelBinderMap[kind] {
return bindingProvider.viewModel(for: model, context: context)
} else {
return cachedViewModel(for: model).viewModel
}
}
fileprivate func cachedViewModel(for model: Model) -> CachedViewModel {
// Supplementary items don't necessarily have an item associated with them (think section headers for empty
// sections) - so handle the "zero" case here.
if let zeroModel = model as? CollectionZeroItemModel {
return CachedViewModel(
viewModel: CollectionZeroItemViewModel(indexPath: zeroModel.indexPath),
preferredLayout: .none)
}
// Return cached view model if there is one.
if let viewModel = viewModelCache[model.modelId] {
return viewModel
}
// Do binding.
let viewModel = modelBinder.viewModel(for: model, context: context)
let cachedViewModel = CachedViewModel(viewModel: viewModel, preferredLayout: .none)
viewModelCache[model.modelId] = cachedViewModel
return cachedViewModel
}
private func handleCollectionEvent(_ event: CollectionEvent) {
switch collectionViewState {
case .loading:
// The collection changed, but the CollectionView hasn't asked for any information yet, so there's nothing to do.
break
case .animating:
// CollectionView is currently animating, so indicate further updates are required when it's done.
collectionViewState = .animatingWithPendingChanges
case .animatingWithPendingChanges:
// More changes? No problem.
break
case .synced:
// Everyone is idle so kick off an update.
applyCurrentDataToCollectionView()
}
}
fileprivate func applyCurrentDataToCollectionView() {
precondition(collectionViewState == .synced)
let (updates, commitCollectionChanges) = currentCollection.beginUpdate(underlyingCollection)
guard updates.hasUpdates else {
// Still synced - no need to fire a collection view update pass.
// However, if there are no updates, the underlying case may still change (e.g. .loading(_) -> .error(_)),
// so a commit is still needed.
if underlyingCollection.state.isDifferentCase(than: currentCollection.state) {
commitCollectionChanges()
}
return
}
observers.notify(.willUpdateItems(updates))
commitCollectionChanges()
for invalidatedModelId in updates.removedModelIds {
viewModelCache[invalidatedModelId] = nil
}
handleUpdateItems(updates) { [weak self] in
self?.observers.notify(.didUpdateItems(updates))
}
}
fileprivate func updatesShouldFallbackOnFullReload(_ updates: CollectionEventUpdates) -> Bool {
// If `NoneReloadOnly` is specified, always reload.
if case .noneReloadOnly = updateAnimationStyle {
return true
}
// There is a long-standing `UICollectionView` bug where adding the first item or removing the last item within
// a section can cause an internal exception. This method detects those cases and returns `true` if the update
// should use a full data reload.
return updates.containsFirstAddInSection || updates.containsLastRemoveInSection
}
fileprivate var collectionViewSectionCount: Int {
return collectionView?.numberOfSections ?? 0
}
}
#if os(iOS)
// MARK: - iOS Data and Batch Updates
extension CollectionViewModelDataSource: UICollectionViewDataSource {
// MARK: Private
public func handleUpdateItems(_ updates: CollectionEventUpdates, completion: @escaping () -> Void) {
// preconditions
precondition(collectionViewState == .synced) // but not for long!
precondition(updates.hasUpdates)
guard let collectionView = collectionView else {
fatalError("handleUpdateItems should never be called without a collectionView")
}
// If the collection view is not part of the window hierarchy or the application is in the background,
// then just do a basic reload. This avoids potential exceptions inside `UICollectionView` when a batch
// update spans the view being added to the hierarchy and avoids core animation queuing up animations
// of changes from when the app was in the background.
if collectionView.window == nil || inBackground {
viewModelCache.removeAll()
// Disable animations during background/offscreen reload.
CATransaction.begin()
CATransaction.setDisableActions(true)
// CollectionView.reloadData does not synchronously fetch new information from the data source, so
// don't call performBatchUpdates until it does.
// NOTE: this path does not fire any observable events
collectionViewState = .loading
collectionView.reloadData()
CATransaction.commit()
completion()
return
}
// Workaround classic collection view bug where some updates require using a full reload.
let fullReloadFallback = updatesShouldFallbackOnFullReload(updates)
// Determine if this should be animated.
let shouldAnimate = shouldAnimateUpdates(updates) && !fullReloadFallback
// Set transaction start if animated.
if !shouldAnimate {
CATransaction.begin()
CATransaction.setDisableActions(true)
}
// Define the post-update completion block.
let completionHandler = { [weak self] (finished: Bool) in
if !shouldAnimate {
CATransaction.commit()
}
if let strongSelf = self {
switch strongSelf.collectionViewState {
case .loading:
fatalError("Precondition failure - state cannot transition from animating to loading")
case .animating:
strongSelf.collectionViewState = .synced
case .animatingWithPendingChanges:
strongSelf.collectionViewState = .synced // applyCurrentDataToCollectionView will update
strongSelf.applyCurrentDataToCollectionView()
case .synced:
fatalError("Precondition failure - state cannot transition from animating to synced")
}
}
completion()
}
// If a full reload is needed, do so and exit early.
guard !fullReloadFallback else {
// On iOS `reloadData` doesn't always dequeue new cells, so remove and add all sections here.
let oldSectionCount = collectionViewSectionCount
let newSectionCount = currentCollection.sections.count
viewModelCache.removeAll()
collectionViewState = .animating
collectionView.performBatchUpdates({
collectionView.deleteSections(IndexSet(integersIn: 0..<oldSectionCount))
collectionView.insertSections(IndexSet(integersIn: 0..<newSectionCount))
}, completion: completionHandler)
return
}
// Do actual batch updates.
collectionViewState = .animating
collectionView.performBatchUpdates({
// Note: The ordering below is important and should not change. See note in
// `CollectionEventUpdates`
let removedSections = updates.removedSections
if !removedSections.isEmpty {
collectionView.deleteSections(IndexSet(removedSections))
}
let addedSections = updates.addedSections
if !addedSections.isEmpty {
collectionView.insertSections(IndexSet(addedSections))
}
let removed = updates.removedModelPaths
if !removed.isEmpty {
collectionView.deleteItems(at: removed.map { $0.indexPath })
}
let added = updates.addedModelPaths
if !added.isEmpty {
collectionView.insertItems(at: added.map { $0.indexPath })
}
for move in updates.movedModelPaths {
collectionView.moveItem(at: move.from.indexPath, to: move.to.indexPath)
}
}, completion: completionHandler)
// Note that reloads are done outside of the batch update call because they're basically unsupported
// alongside other complicated batch updates. Because reload actually does a delete and insert under
// the hood, the collectionview will throw an exception if that index path is touched in any other way.
// Splitting the call out here ensures this is avoided.
let updated = updates.updatedModelPaths
if !updated.isEmpty {
var indexPathsToReload: [IndexPath] = []
let size = collectionView.bounds
updated.forEach { indexPath in
var oldCachedViewModel: CachedViewModel?
var newCachedViewModel: CachedViewModel?
// Clear cache for updated items.
if let item: Model = currentCollection.atModelPath(indexPath) {
oldCachedViewModel = viewModelCache.removeValue(forKey: item.modelId)
}
// Create new view models from the updated models.
if let model: Model = currentCollection.atModelPath(indexPath) {
_ = cachedViewModel(for: model)
// Update the size.
// TODO:(wkiefer) Probably should cache last known available size - this makes some assumptions
// about available size.
let availableSize = AvailableSize(CGSize(width: size.width, height: CGSize.maxWindowSize.height))
_ = preferredLayoutForItemAtIndexPath(indexPath.indexPath, availableSize: availableSize)
newCachedViewModel = viewModelCache[model.modelId]
}
// If the size hasn't changed, simply rebind the view rather than perform a full cell reload.
if let old = oldCachedViewModel,
let new = newCachedViewModel , old.preferredLayout == new.preferredLayout {
rebindViewAtIndexPath(indexPath.indexPath, toViewModel: new.viewModel)
} else {
indexPathsToReload.append(indexPath.indexPath)
}
}
if !indexPathsToReload.isEmpty {
collectionView.reloadItems(at: indexPathsToReload)
}
}
}
fileprivate func rebindViewAtIndexPath(_ indexPath: IndexPath, toViewModel viewModel: ViewModel) {
guard let collectionView = collectionView else { return }
guard let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewHostCell else { return }
willRebindViewModel(viewModel)
cell.hostedView?.bindToViewModel(viewModel)
}
// MARK: UICollectionViewDataSource
public func numberOfSections(in collectionView: UICollectionView) -> Int {
switch collectionViewState {
case .loading:
_ = currentCollection.update(underlyingCollection)
collectionViewState = .synced
default:
break
}
return currentCollection.sections.count
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
precondition(collectionViewState != .loading)
if currentCollection.sections.indices.contains(section) {
return currentCollection.sections[section].count
}
return 0
}
public func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
precondition(collectionViewState != .loading)
// Fetch the model item and view model.
let modelItem = currentCollection.sections[indexPath.section][indexPath.item]
var cachedViewModel = self.cachedViewModel(for: modelItem)
let viewModel = cachedViewModel.viewModel
// Get the view class that will bind to the view model.
let viewType = viewBinder.viewTypeForViewModel(viewModel, context: context)
// Register the view/model pair to optimize reuse.
let reuseId = reuseIdProvider.reuseIdForViewModel(viewModel, viewType: viewType)
collectionView.register(CollectionViewHostCell.self, forCellWithReuseIdentifier: reuseId)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath)
cell.backgroundColor = collectionViewBackgroundColor
if let hostCell = cell as? CollectionViewHostCell {
var reuseView: View?
// Determine if there is already a hosted view that matches the view class - if so, it can be reused as is.
if let hostUIView = hostCell.hostedView as? UIView , type(of: hostUIView) == viewType {
reuseView = hostCell.hostedView
}
// Bust the layout cache if it's stale.
if let layout = cachedViewModel.preferredLayout.layout , !layout.validCache(forViewModel: viewModel) {
// TODO:(danielh) This has the same issue as the update where it assumes available size.
let maxSize = CGSize(width: collectionView.bounds.width, height: CGSize.maxWindowSize.height)
let availableSize = AvailableSize(maxSize)
cachedViewModel.preferredLayout = viewBinder.preferredLayout(
fitting: availableSize,
for: viewModel,
context: context)
viewModelCache[modelItem.modelId] = cachedViewModel
}
let view = viewBinder.view(
for: viewModel,
context: context,
reusing: reuseView,
layout: cachedViewModel.preferredLayout.layout)
hostCell.hostedView = view
}
return cell
}
public func collectionView(
_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath
) -> UICollectionReusableView {
guard let supplementaryViewBinder = supplementaryViewBinderMap[kind] else {
fatalError("Request for supplementary kind (\(kind)) that has no registered view binder.")
}
let viewModel = viewModelForSupplementaryElementAtIndexPath(kind, indexPath: indexPath)
let viewType = supplementaryViewBinder.viewTypeForViewModel(viewModel, context: context)
let reuseId = reuseIdProvider.reuseIdForViewModel(viewModel, viewType: viewType)
collectionView.register(
CollectionViewHostResuableView.self,
forSupplementaryViewOfKind: kind,
withReuseIdentifier: reuseId)
let supplementaryView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: reuseId,
for: indexPath)
if let supplementaryView = supplementaryView as? CollectionViewHostResuableView {
var reuseView: View?
if let hostUIView = supplementaryView.hostedView as? UIView , type(of: hostUIView) == viewType {
reuseView = supplementaryView.hostedView
}
let view = supplementaryViewBinder.view(
for: viewModel, context: context, reusing: reuseView, layout: nil)
supplementaryView.hostedView = view
}
return supplementaryView
}
}
// MARK: - macOS Data and Batch Updates
#elseif os(OSX)
private struct OSInfo {
static let isAtLeastSierra: Bool = {
let sierra = OperatingSystemVersion(majorVersion: 10, minorVersion: 12, patchVersion: 0)
return ProcessInfo.processInfo.isOperatingSystemAtLeast(sierra)
}()
}
private class EmptyCollectionViewItem: NSCollectionViewItem {
public init() {
super.init(nibName: nil, bundle: nil)!
}
required init(coder: NSCoder) {
fatalError("Unsupported initializer")
}
override func loadView() {
view = NSView(frame: .zero)
}
}
extension CollectionViewModelDataSource: NSCollectionViewDataSource {
// MARK: Private
public func handleUpdateItems(_ updates: CollectionEventUpdates, completion: @escaping () -> Void) {
// preconditions
precondition(collectionViewState == .synced) // but not for long!
precondition(updates.hasUpdates)
guard let collectionView = collectionView else {
fatalError("handleUpdateItems should never run without a collectionView")
}
// The standard collection view hierarchy is `NSScrollView`->`NSClipView`->`NSCollectionView`, so finding
// the scroll view via super view chaining is expected.
guard let scrollView = collectionView.superview?.superview as? NSScrollView else {
fatalError("CollectionViewModelDataSource requires an outer scrollview.")
}
log(event: "HandleUpdateItems", updates: updates)
let didProcessUpdatesWithLog: (CollectionEventUpdates) -> Void = { [weak self] updates in
self?.log(event: "DidProcessUpdates", updates: updates)
completion()
}
if shouldPerformFullReload(withCollectionView: collectionView, scrollView: scrollView, updates: updates) {
viewModelCache.removeAll()
guard !OSInfo.isAtLeastSierra else {
let oldSectionCount = collectionView.numberOfSections
let newSectionCount = numberOfSections(in: collectionView)
precondition(Thread.isMainThread)
collectionViewState = .animating
collectionView.performBatchUpdates({
precondition(Thread.isMainThread)
let existingSections = IndexSet(integersIn: 0..<oldSectionCount)
collectionView.deleteSections(existingSections)
collectionView.insertSections(IndexSet(integersIn: 0..<newSectionCount))
}, completionHandler: { [weak self] _ in
precondition(Thread.isMainThread)
didProcessUpdatesWithLog(updates)
self?.advanceCollectionViewStateAfterPerformUpdates()
})
return
}
// CollectionView.reloadData does not synchronously fetch new information from the data source, so
// don't call performBatchUpdates until it does.
collectionViewState = .loading
collectionView.reloadData()
//precondition(collectionViewState != .loading)
// NOTE: This notifies observers of .didUpdateItems before the CollectionView has been updated.
// Presumably this means code that tries to preserve selection across changes will not work if a reload
// is triggered. One option would be to wait until the CollectionView asks for the section count and
// fire the .didUpdateItems event then, but if the CollectionView is hidden that may not happen.
// Not sure what the best option is, besides complaining about how hard it is to use CollectionView.
// Another option: trigger a different event type indicating a reload has started.
didProcessUpdatesWithLog(updates)
return
}
// Determine if this should be animated.
let shouldAnimate = shouldAnimateUpdates(updates)
if shouldAnimate {
// BUGFIX: If the collection view is deallocated during the timespan of the animation, NSCollectionView
// internals will end up calling the non-zeroing weak delegate back and crashing. So retain both the
// delegate and the collection view until the animation completes.
// This is easy to repro by removing the completion handler and increasing the animation duration.
let retainedDelegate = collectionView.delegate
NSAnimationContext.beginGrouping()
NSAnimationContext.current().completionHandler = { [collectionView, retainedDelegate] in
_ = collectionView
_ = retainedDelegate
}
NSAnimationContext.current().duration = 0.2
}
// `performBatchUpdates` doesn't animate away deletes, so as a workaround the deleted items are set to
// alpha of 0 and then restored at the end of the batch.
// TODO(wkiefer): There's likely a better solution here, but not fading them out looks bad.
var forceHiddenItems: [NSCollectionViewItem] = []
collectionViewState = .animating
let cv = shouldAnimate ? collectionView.animator() : collectionView
cv.performBatchUpdates({
// Note: The ordering below is important and should not change. See note in
// `CollectionEventUpdates`
let removedSections = updates.removedSections
if !removedSections.isEmpty {
collectionView.deleteSections(IndexSet(removedSections))
}
let addedSections = updates.addedSections
if !addedSections.isEmpty {
collectionView.insertSections(IndexSet(addedSections))
}
let removed = updates.removedModelPaths
if !removed.isEmpty {
let removedIndexPathSet = Set(removed.map { $0.indexPath })
let visibleIndexPaths = collectionView.indexPathsForVisibleItems()
// Workaround for `NSCollectionView` not removing the items until the end.
for indexPath in removedIndexPathSet.intersection(visibleIndexPaths) {
if let item = collectionView.item(at: indexPath) {
item.view.alphaValue = 0
forceHiddenItems.append(item)
}
}
collectionView.deleteItems(at: removedIndexPathSet)
}
let added = updates.addedModelPaths
if !added.isEmpty {
collectionView.insertItems(at: Set(added.map { $0.indexPath } ))
}
let movedModels = updates.movedModelPaths
if !movedModels.isEmpty {
let usingFakeMoves = shouldFakeMoves(updates: updates)
for move in movedModels {
// Clear cache for moved items.
// NOTE: currentCollection has been updated to the latest data at this point.
if let item: Model = currentCollection.atModelPath(move.to) {
viewModelCache[item.modelId] = nil
}
if usingFakeMoves {
collectionView.deleteItems(at: [move.from.indexPath])
collectionView.insertItems(at: [move.to.indexPath])
} else {
collectionView.moveItem(at: move.from.indexPath, to: move.to.indexPath)
}
}
}
}) { [weak self] (finished: Bool) in
// Restore alpha on item views.
forceHiddenItems.forEach { $0.view.animator().alphaValue = 1.0 }
didProcessUpdatesWithLog(updates)
self?.advanceCollectionViewStateAfterPerformUpdates()
}
// Note that reloads are done outside of the batch update call because they're basically unsupported
// alongside other complicated batch updates. Because reload actually does a delete and insert under
// the hood, the collectionview will throw an exception if that index path is touched in any other way.
// Splitting the call out here ensures this is avoided.
let updated = updates.updatedModelPaths
if !updated.isEmpty {
var reloadSet = Set<IndexPath>()
let size = collectionView.bounds
for indexPath in updated {
var oldCachedViewModel: CachedViewModel?
var newCachedViewModel: CachedViewModel?
// Clear cache for updated items.
if let item: Model = currentCollection.atModelPath(indexPath) {
oldCachedViewModel = viewModelCache.removeValue(forKey: item.modelId)
}
// Create new view models from the updated models.
if let model: Model = currentCollection.atModelPath(indexPath) {
_ = cachedViewModel(for: model)
// Update the size.
// TODO:(wkiefer) Probably should cache last known available size - this makes some assumptions
// about available size.
let availableSize = AvailableSize(CGSize(width: size.width, height: CGSize.maxWindowSize.height))
_ = preferredLayoutForItemAtIndexPath(indexPath.indexPath, availableSize: availableSize)
newCachedViewModel = viewModelCache[model.modelId]
}
// If the size hasn't changed, simply rebind the view rather than perform a full cell reload.
if let old = oldCachedViewModel,
let new = newCachedViewModel , old.preferredLayout == new.preferredLayout {
rebindViewAtIndexPath(indexPath.indexPath, toViewModel: new.viewModel)
} else {
reloadSet.insert(indexPath.indexPath)
}
}
if !reloadSet.isEmpty {
collectionView.reloadItems(at: reloadSet)
}
}
if shouldAnimate {
NSAnimationContext.endGrouping()
}
}
private func log(event: String, updates: CollectionEventUpdates) {
/*
// Accessing the CollectionView here causes it to query the data source which trips some invariant checks.
// Sierra calls numberOfItemsInSection before numberOfSections ???
let collectionViewStatus: String = {
if let collectionView = collectionView {
let sectionCounts = (0..<collectionView.numberOfSections).map {
collectionView.numberOfItems(inSection: $0)
}
return "Sections: \(sectionCounts) Bounds: \(collectionView.bounds)"
} else {
return "nil"
}
}()
Log.verbose("pilot.ui", message: "\(event) View \(collectionViewStatus)")
let modelStatus: String = {
let sectionCounts = currentCollection.sections.map { $0.count }
return "Sections: \(sectionCounts)"
}()
Log.verbose("pilot.ui", message: "\(event) Model(\(currentCollection.collectionId)) \(modelStatus)")
let describe: ([ModelPath]) -> String = { paths in
if paths.isEmpty { return "None" }
return paths.map({ return "(\($0.sectionIndex), \($0.itemIndex))" }).joined(separator: ",")
}
let addedSections = updates.addedSections
.map { String($0) }
.joined(separator: ",")
let addedItems = updates.addedModelPaths
let movedFrom = updates.movedModelPaths.map { $0.from }
let movedTo = updates.movedModelPaths.map { $0.to }
let updateDescription = [
"AddedSections: [\(addedSections)]",
"Added: [\(describe(addedItems))]",
"Updated: [\(describe(updates.updatedModelPaths))]",
"Removed: [\(describe(updates.removedModelPaths))]",
"Moved: [(\(describe(movedFrom))) > (\(describe(movedTo)))]"
].joined(separator: " ")
precondition(Thread.isMainThread)
Log.verbose("pilot.ui", message: "\(event) Updates \(updateDescription)")
*/
}
private func advanceCollectionViewStateAfterPerformUpdates() {
switch collectionViewState {
case .loading:
fatalError("Precondition failure - state cannot transition from animating to loading")
case .animating:
collectionViewState = .synced
case .animatingWithPendingChanges:
collectionViewState = .synced // applyCurrentDataToCollectionView will update
applyCurrentDataToCollectionView()
case .synced:
fatalError("Precondition failure - state cannot transition from animating to synced")
}
}
private func rebindViewAtIndexPath(_ indexPath: IndexPath, toViewModel viewModel: ViewModel) {
guard let collectionView = collectionView else { return }
guard let item = collectionView.item(at: indexPath as IndexPath) as? CollectionViewHostItem else { return }
willRebindViewModel(viewModel)
item.hostedView?.bindToViewModel(viewModel)
}
private func shouldFakeMoves(updates: CollectionEventUpdates) -> Bool {
if updates.movedModelPaths.isEmpty {
return false
}
// NSCollectionView throws an exception when moveItem is called with a `to` IndexPath that is the
// last item in a different section than the `from`, instead of catching this specific case, all
// moves across sections do a delete and an insert.
for move in updates.movedModelPaths {
if move.from.sectionIndex != move.to.sectionIndex {
return true
}
}
// If there are any other updates, always perform a delete and insert to avoid invalid index path
// exception
// TODO:(danielh) Followup with more investigation on the underlying NSCollectionView problem and try to
// come up with better fix
var updatesWithoutMoved = updates
updatesWithoutMoved.movedModelPaths = []
return updatesWithoutMoved.hasUpdates
}
private func shouldPerformFullReload(
withCollectionView collectionView: NSCollectionView,
scrollView: NSScrollView,
updates: CollectionEventUpdates
) -> Bool {
// If no window, fallback on full reload.
if collectionView.window == nil {
return true
}
// If `NoneReloadOnly` is specified, always reload.
if case .noneReloadOnly = updateAnimationStyle {
return true
}
// `performBatchUpdates` will segfault if called on a collectionview with no height or width, so
// reload in that case.
let insets = scrollView.contentInsets
var size = collectionView.collectionViewLayout?.collectionViewContentSize ?? NSSize.zero
size.height -= insets.top + insets.bottom
size.width -= insets.left + insets.right
if size.height < 1.0 || size.width < 1.0 {
return true
}
// If no sections, just reload. Fixes a segfault messaging a dead object in performBatchUpdates.
if currentCollection.sections.count == 0 {
return true
}
// If adding first item or removing last item, reload to avoid a crash in NSCollectionView.
// macOS 10.12 will crash when removing the last item, and sometimes a crash will occur in layout
// when adding the first item.
return updates.containsFirstAddInSection || updates.containsLastRemoveInSection
}
// MARK: NSCollectionViewDataSource
private func syncData() {
switch collectionViewState {
case .loading:
currentCollection.update(underlyingCollection)
collectionViewState = .synced
default:
break
}
}
public func numberOfSections(in collectionView: PlatformCollectionView) -> Int {
syncData()
return currentCollection.sections.count
}
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
/// HACK: Sierra sometimes calls numberOfItemsInSection before numberOfSections, so sync the data in this case too.
syncData()
if currentCollection.sections.indices.contains(section) {
return currentCollection.sections[section].count
}
return 0
}
public func collectionView(
_ collectionView: NSCollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath
) -> NSView {
guard let supplementaryViewBinder = supplementaryViewBinderMap[kind] else {
fatalError("Request for supplementary kind (\(kind)) that has no registered view binder.")
}
let viewModel = viewModelForSupplementaryElementAtIndexPath(kind, indexPath: indexPath)
let viewType = supplementaryViewBinder.viewTypeForViewModel(viewModel, context: context)
let reuseId = "\(NSStringFromClass(viewType))-\(type(of: viewModel))"
collectionView.register(
viewType,
forSupplementaryViewOfKind: kind,
withIdentifier: reuseId)
let supplementaryView = collectionView.makeSupplementaryView(
ofKind: kind,
withIdentifier: reuseId,
for: indexPath as IndexPath)
if let supplementaryView = supplementaryView as? View {
supplementaryView.bindToViewModel(viewModel)
}
return supplementaryView
}
public func collectionView(
_ collectionView: NSCollectionView,
itemForRepresentedObjectAt indexPath: IndexPath
) -> NSCollectionViewItem {
precondition(collectionViewState != .loading)
// Fetch the model item and view model.
let sections = currentCollection.sections
guard let modelItem = sections[safe: indexPath.section]?[safe: indexPath.item] else {
// NSCollectionView occasionally asks for an item outside of the current collection.
// In that case, return a zero-size view and hope NSCollectionView refreshes itself later.
// TODO:(ca) dig into this scenario for real and file a radar issue upstream
return EmptyCollectionViewItem()
}
var cachedViewModel = self.cachedViewModel(for: modelItem)
let viewModel = cachedViewModel.viewModel
// Get the view class that will bind to the view model.
let viewType = viewBinder.viewTypeForViewModel(viewModel, context: context)
// Register the view/model pair to optimize reuse.
let reuseId = "\(NSStringFromClass(viewType))-\(type(of: viewModel))"
collectionView.register(CollectionViewHostItem.self, forItemWithIdentifier: reuseId)
let item = collectionView.makeItem(withIdentifier: reuseId, for: indexPath)
if let hostItem = item as? CollectionViewHostItem {
var reuseView: View?
// Determine if there is already a hosted view that matches the view class - if so, it can be reused as is.
if let hostUIView = hostItem.hostedView as? NSView , type(of: hostUIView) == viewType {
reuseView = hostItem.hostedView
}
// Bust the layout cache if its stale.
if let layout = cachedViewModel.preferredLayout.layout , !layout.validCache(forViewModel: viewModel) {
// TODO:(danielh) This has the same issue as the update where it assumes available size.
let maxSize = CGSize(width: collectionView.bounds.width, height: CGSize.maxWindowSize.height)
let availableSize = AvailableSize(maxSize)
cachedViewModel.preferredLayout = viewBinder.preferredLayout(
fitting: availableSize,
for: viewModel,
context: context)
viewModelCache[modelItem.modelId] = cachedViewModel
}
let view = viewBinder.view(
for: viewModel,
context: context,
reusing: reuseView,
layout: cachedViewModel.preferredLayout.layout)
hostItem.hostedView = view
}
return item
}
}
#endif // os(OSX)
/// Helper struct representing cached data for a `ViewModel`.
private struct CachedViewModel {
var viewModel: ViewModel
var preferredLayout: PreferredLayout
}
extension CGSize {
fileprivate static var maxWindowSize: CGSize {
// AppKit maximum window size.
return CGSize(width: 10000, height: 10000)
}
}
| [
-1
] |
63f4c452c5fa4f5c12e7af3ca4d0e1b205933a32 | cdb9779e4227529075af649b72b713b241c3cefb | /pg1/ViewController.swift | 2504c3b224331434a76436f9179d6e1dca1d610c | [] | no_license | princybaby/pg1 | cf5c7ef6d4b0b60d13c4fe220d26ced0a32b7751 | 547156cfd22b09e8e4611288bf5008a4c7bb6d40 | refs/heads/master | 2020-09-12T06:12:58.527211 | 2016-09-06T07:25:39 | 2016-09-06T07:25:39 | 67,483,984 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 504 | swift | //
// ViewController.swift
// pg1
//
// Created by Don Dominic Mathew on 24/08/16.
// Copyright © 2016 Jesusdi. 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.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
293888,
279041,
288501,
277508,
279046,
277512,
215562,
275466,
278543,
234511,
281107,
279064,
236057,
286234,
281118,
282145,
284197,
289318,
296487,
296489,
304174,
309807,
300086,
234551,
279096,
286775,
300089,
234043,
288827,
238653,
226878,
237624,
288321,
277057,
286786,
129604,
301637,
284740,
226887,
293961,
243786,
300107,
286796,
158285,
226896,
212561,
284242,
292435,
228945,
300629,
276054,
237655,
307288,
300116,
212573,
40545,
200802,
284261,
281703,
306791,
286314,
296042,
356460,
164974,
307311,
281202,
284275,
277108,
300149,
314996,
276087,
287350,
281205,
234619,
292478,
284287,
292990,
284289,
278657,
276612,
280710,
284298,
303242,
278157,
311437,
226447,
285837,
234641,
278675,
349332,
282262,
117399,
280219,
284315,
284317,
282270,
285855,
228000,
299165,
302235,
282275,
278693,
287399,
284328,
100521,
234665,
313007,
284336,
277171,
307379,
284341,
286390,
300727,
276150,
280760,
282301,
277696,
285377,
280770,
227523,
302788,
228551,
279751,
280775,
279754,
282311,
230604,
284361,
276686,
298189,
282320,
229585,
302286,
307410,
287437,
313550,
280790,
189655,
302295,
226009,
282329,
363743,
282338,
298211,
284391,
277224,
228585,
282346,
358127,
312049,
286963,
289524,
280821,
120054,
226038,
234232,
282357,
280826,
286965,
358139,
282365,
286462,
280824,
280832,
282368,
276736,
358147,
226055,
282377,
299786,
312586,
295696,
300817,
282389,
296216,
282393,
329499,
281373,
228127,
287007,
315170,
282403,
281380,
282917,
152356,
233767,
234279,
283433,
130346,
282411,
293682,
159541,
285495,
282426,
289596,
283453,
307516,
279360,
289088,
289600,
288579,
293700,
238920,
234829,
287055,
307029,
295766,
241499,
188253,
308064,
227688,
313706,
290303,
306540,
299374,
293742,
162672,
199024,
276849,
216433,
278897,
292730,
333179,
207738,
303998,
290175,
275842,
224643,
313733,
183173,
304008,
324491,
304012,
234380,
304015,
300432,
226705,
310673,
227740,
277406,
285087,
289697,
234402,
289187,
284580,
283556,
284586,
144811,
276396,
291755,
286126,
277935,
324528,
282035,
282548,
292277,
296374,
130487,
234423,
277432,
278968,
281530,
293308,
278973,
291774,
295874,
299973,
165832,
306633,
289224,
288205,
286158,
280015,
310734,
301012,
301016,
163289,
286175,
234465,
168936,
294889,
231405,
183278,
282095,
286189,
277487,
298989,
227315,
296436,
308721,
281078,
237556,
290299,
233980,
287231
] |
4031939fc94d8908aa0ea66f093865088341e492 | a347f34dce0f20ddc5436160952a45949bd9a039 | /Mastering_Animation/Blooming View/CircularTransition.swift | cfad48550f2b9971ccc1884e8fdafeb2d17e76fc | [] | no_license | ScutiUY/Mastering_Animation | 7795daa3a52b0df3d1900c11159521e9b0310415 | cb85aea41d49d20a1dae7537601a5f82658d2ec2 | refs/heads/master | 2023-01-09T15:09:50.648638 | 2020-11-13T19:52:16 | 2020-11-13T19:52:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,250 | swift | //
// CircularTransition.swift
// Mastering_Animation
//
// Created by 신의연 on 2020/08/05.
// Copyright © 2020 Koggy. All rights reserved.
//
import UIKit
class CircularTransition: NSObject {
var circle = UIView()
var startingPoint: CGPoint = .zero {
didSet {
circle.center = startingPoint
}
}
var circleColor = UIColor.white
var duration = 0.3
enum CircularTransitionMode {
case present, dismiss, pop
}
var transitionMode: CircularTransitionMode = .present
}
extension CircularTransition: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
var containerView = transitionContext.containerView
if transitionMode == .present {
if let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
let viewCenter = presentedView.center
let viewSize = presentedView.frame.size
}
} else {
}
}
}
| [
-1
] |
a2402aaee9c2b2f19ea82c4ed2e207591651ace2 | f451c9ef9adf5e254cd11b554d5d8127d4fea457 | /PocketCast/Helpers/TimeInterval+Util.swift | 053d7cec22ece91e1c2361c54ca3eabd4c9a48d7 | [] | no_license | stuartjmoore/Pocket-Casts | 663477367233e2a6066fdd16ecfb09d4c6b291f0 | 23aa3ad58cfe2d39814813bed487896a29b674d3 | refs/heads/master | 2020-04-05T22:53:09.406623 | 2020-04-05T16:14:55 | 2020-04-05T16:14:55 | 40,014,525 | 48 | 5 | null | 2020-04-05T16:14:56 | 2015-07-31T16:32:46 | Swift | UTF-8 | Swift | false | false | 838 | swift | //
// TimeInterval+Util.swift
// Pocket Casts
//
// Created by Stuart Moore on 10/3/17.
// Copyright © 2017 Morten Just Petersen. All rights reserved.
//
import Foundation
extension TimeInterval {
var asClock: String {
let formatter = NumberFormatter()
formatter.minimumIntegerDigits = 2
let hours = Int(self / 3600)
let minutes = Int((truncatingRemainder(dividingBy: 3600)) / 60)
let seconds = Int(truncatingRemainder(dividingBy: 60))
let hoursString = formatter.string(from: NSNumber(integerLiteral: hours)) ?? ""
let minutesString = formatter.string(from: NSNumber(integerLiteral: minutes)) ?? ""
let secondsString = formatter.string(from: NSNumber(integerLiteral: seconds)) ?? ""
return "\(hoursString):\(minutesString):\(secondsString)"
}
}
| [
-1
] |
5bfd58556f72ac5f0da60de2a6a55be19aa4c186 | 39200464ee38428f20ee3534e11ca33e988edd5b | /Fruit App/Logger/Logger.swift | df810eb988da4fcbc8b1df6daccbd243b2c35012 | [] | no_license | edwardelizibethhoffr/fruit_app | 978a4f9246353e38d899b8962847c2ea68931803 | 78c662de91cdda757da5279f8ef7ac8de2af192a | refs/heads/main | 2023-05-28T08:00:48.850141 | 2021-06-20T23:56:30 | 2021-06-20T23:56:30 | 378,755,808 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 551 | swift | //
// Logger.swift
// Fruit App
//
// Created by Calum Maclellan on 19/06/2021.
//
import Foundation
struct Logger: LoggerProtocol {
private let apiLogger: APILoggingProtocol
init(_ apiLogger: APILoggingProtocol = APIService()) {
self.apiLogger = apiLogger
}
func makeLoggingRequest(eventType: UsageEventType, data: String) {
apiLogger.makeUsageEventRequest(eventType: eventType, data: data)
}
}
protocol LoggerProtocol {
func makeLoggingRequest(eventType: UsageEventType, data: String)
}
| [
-1
] |
e2f2b5bc1c8b8813e58538197fec716942ea4238 | 0046432afc4125ba2b8252f1c30262477b06e918 | /Use cases/Authenticate with provider/Models/PoPToken.swift | 1f1c4bf44d8ed156e9f414111f24560287e58419 | [] | no_license | wrmack/Get-tokens | 9c15f891d3d5fd14898d51d0a1ae53c0ad26377b | 4ff5db65f505dadccecc056b8a83c7bd6367c649 | refs/heads/master | 2021-08-01T23:05:56.366150 | 2021-07-23T01:39:33 | 2021-07-23T01:39:33 | 169,650,080 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 12,678 | swift | //
// PoPToken.swift
// POD browser
//
// Created by Warwick McNaughton on 26/01/19.
// Copyright © 2019 Warwick McNaughton. All rights reserved.
//
/*
https://github.com/solid/oidc-rp/blob/master/src/PoPToken.js
https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture-08
https://tools.ietf.org/html/draft-ietf-oauth-pop-key-distribution-04
https://tools.ietf.org/html/rfc7800
https://github.com/solid/solid-auth-client
http://www.thread-safe.com/2015/01/proof-of-possession-putting-pieces.html
https://umu.diva-portal.org/smash/get/diva2:1243880/FULLTEXT01.pdf
https://www.iana.org/assignments/jwt/jwt.xhtml#confirmation-methods (all the acronyms)
Questions:
Does Solid use symmetric or asymmetric keys?
Who sends what to whom and when?
How generate a public / private key in JWK format?
The code for AuthenticationRequest.js shows private and public keys:
https://github.com/solid/oidc-rp/blob/master/src/AuthenticationRequest.js
This is the asymmetric keys model.
This indicates the pop confirmation key is assigned to the 'request' parameter (line 148):
https://github.com/solid/oidc-op/blob/master/src/handlers/AuthenticationRequest.js
=====
OAuth PoP key distribution docs give two versions (ver 03 cf 04 of doc) with one using a RSA public key and the other an ECC public key:
https://tools.ietf.org/rfcdiff?url2=draft-ietf-oauth-pop-key-distribution-04.txt
"As shown in Figure 6 the content of the 'key' parameter contains the As shown in Figure 6 the content of the 'req_cnf' parameter contains
RSA public key the client would like to associate with the access the ECC public key the client would like to associate with the access
token. token (in JSON format).
POST /token HTTP/1.1 POST /token HTTP/1.1
Host: server.example.com Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded;charset=UTF-8 Content-Type: application/x-www-form-urlencoded;charset=UTF-8
grant_type=authorization_code grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA &code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
&token_type=pop &token_type=pop
&alg=RS256 &req_cnf=eyJhbGciOiJSU0ExXzUi ..
&key=eyJhbGciOiJSU0ExXzUi ...
(remainder of JWK omitted for brevity) (remainder of JWK omitted for brevity)"
=====
=====
An example of a successful response is shown in Figure 7. An example of a successful response is shown in Figure 7.
HTTP/1.1 200 OK HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8 Content-Type: application/json;charset=UTF-8
Cache-Control: no-store Cache-Control: no-store
Pragma: no-cache Pragma: no-cache
{ {
"access_token":"2YotnFZFE....jr1zCsicMWpAA", "access_token":"2YotnFZFE....jr1zCsicMWpAA",
"token_type":"pop", "token_type":"pop",
"alg":"RS256",
"expires_in":3600, "expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA" "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
} }
The access code contains a JWT:
{ {
"iss":"xas.example.com", "iss":"xas.example.com",
"aud":"http://auth.example.com", "aud":"http://auth.example.com",
"exp":"1361398824", "exp":"1361398824",
"nbf":"1360189224", "nbf":"1360189224",
"cnf":{ "cnf":{
"jwk":{"kty":"RSA", "jwk" : {
"n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx "kty" : "EC",
4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs "kid" : h'11',
tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2 "crv" : "P-256",
QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI "x" : b64'usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8',
SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb "y" : b64'IBOL+C3BttVivg+lSreASjpkttcsz+1rb7btKLv8EX4'
w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw", }
"e":"AQAB",
"alg":"RS256",
"kid":"id123"}
} }
} }
=====
In browser, select log in to inrupt using web inspector on the login popup.
A GET request is sent to https://inrupt.net/login with query params
scope: openid
client_id
response_type: id_token token
request: is JWT -
https://jwt.io/#debugger-io?token=eyJhbGciOiJub25lIn0.eyJyZWRpcmVjdF91cmkiOiJodHRwczovL3dybWFjay5pbnJ1cHQubmV0Ly53ZWxsLWtub3duL3NvbGlkL2xvZ2luIiwiZGlzcGxheSI6InBhZ2UiLCJub25jZSI6Im1fTUhLZ1FtM0JwdXJhMDlHSU1zT3BsMHQ4OGNjTmc2VVM1dzYtcFdrMVUiLCJrZXkiOnsiYWxnIjoiUlMyNTYiLCJlIjoiQVFBQiIsImV4dCI6dHJ1ZSwia2V5X29wcyI6WyJ2ZXJpZnkiXSwia3R5IjoiUlNBIiwibiI6IjNUaHBkTXRuNmxOcmFfcEZDWTYyQ1dlRWxVUTFWRWdiQWJuY0hZc1c3MFhEZzZzT1hvd201M1dISmRfQUdTSW15b2pXTDFhU2JaTjBiUGNJUzhmbjg0cEFHNHV2VS1BRV9WUTk2SmhYSlJ3UmNLdjRsenBtYnJsNmpTX1RST1RCZWhWSGhkbXNaVGxsVV93U29CYmhkVVhyb1dmOUt3Unk2NFFCZk95Ry1zd3dVLVlQMGRJdmgyUXFzM2JLQ3YwdmlHNk02eG9BVjRxY3JROHVHNWh3Mk95MFZHM1B4VTljYlVxSFJvbk9WbnB2ZEh0elJaTEFxMnRXd0REMTdwQV9LbkVXa3Z4ZzRxcmN6SW5WM3ZRYXVJalEtcmpzMnJWRlJTel9sV19ieDk4QnNLOWJyckEtMWpqLThNdVRVRkdiTUhqelhrekRfVlZ2YkFKV1lEX0VfdyJ9fQ.%26state%3D9LJFstftfMc_m0YRx65SxdRB8fgGvc10hRsx2ZDVJYA
state:
Press log in button: [couldn't capture anything because popup gets dismissed]
In browser attempt to access prefs.ttl file and view the requests / responses in web inspector. The request sends a PoPToken:
https://jwt.io/#debugger-io?token=eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJlMjkxZWY0NmE5YmU0ODJlMTgxZWVhYWNiZmViODNkNSIsImF1ZCI6Imh0dHBzOi8vd3JtYWNrLmlucnVwdC5uZXQiLCJleHAiOjE1NDg0OTQyMTMsImlhdCI6MTU0ODQ5MDYxMywiaWRfdG9rZW4iOiJleUpoYkdjaU9pSlNVekkxTmlJc0ltdHBaQ0k2SW5aYWFVTmtaR1ZJYkhRMEluMC5leUpwYzNNaU9pSm9kSFJ3Y3pvdkwybHVjblZ3ZEM1dVpYUWlMQ0p6ZFdJaU9pSm9kSFJ3Y3pvdkwzZHliV0ZqYXk1cGJuSjFjSFF1Ym1WMEwzQnliMlpwYkdVdlkyRnlaQ050WlNJc0ltRjFaQ0k2SW1VeU9URmxaalEyWVRsaVpUUTRNbVV4T0RGbFpXRmhZMkptWldJNE0yUTFJaXdpWlhod0lqb3hOVFE1TkRNMU5qWTRMQ0pwWVhRaU9qRTFORGd5TWpZd05qZ3NJbXAwYVNJNklqVTVOMll6T1dabE1qRXpabU5rWmpRaUxDSnViMjVqWlNJNklpMUtSMlUwTjFkdmJYRm5ZVGRTWDB0R1kxTnRPV1ZsUVRoT1drRlFabXRyUzBzd2FWcHJaM0JGTFc4aUxDSmhlbkFpT2lKbE1qa3haV1kwTm1FNVltVTBPREpsTVRneFpXVmhZV05pWm1WaU9ETmtOU0lzSW1OdVppSTZleUpxZDJzaU9uc2lZV3huSWpvaVVsTXlOVFlpTENKbElqb2lRVkZCUWlJc0ltVjRkQ0k2ZEhKMVpTd2lhMlY1WDI5d2N5STZXeUoyWlhKcFpua2lYU3dpYTNSNUlqb2lVbE5CSWl3aWJpSTZJakpWT1haNGJtOVhOVlkwUldseFZFZFdXR0ZoWjNoUVVGVnJZbWw1UTB0NFdrdFJMVkZ6TjBoRFdWOVZURUZyVVd0amNXSlpRM0V4ZWs1YWFraFBWa1pWY25CV1dpMXVWM0pQZWtjNU1qSjZVelkzU0hWUk5XeGxibXBGTmkwNFVsZERWbWRrVG1ScFJqaERaMmxUVmkwMFJIQkRhMkZRUzNZelIxaDRha0Z1VUhwa2RrdFhNbmc0UzJObVdWQmZZWE41Vkd0NmFIUlNPUzAzYVU0d1NGaFRhWGRJVkVKRWNUVlJjR2hxYmtOUFptaDJOMmh0V21WaVlVaFhXbFJGUkhkQlRXOXJVbnBDUkZkMk1EVXdSM0ZFYTBkc1IzQkllRk5wVVVaMGJUVkJUSE5TZFZoeVNFRklWbFJxTUdkelIyNUNObU5GWDFkbE1rVTVSWGx0YURSWmRGRlRMWEJvWkdKR2VuWXRaM0p1TTA5T2MzaGZZalpWYVhkclRFcGhiRTQyVURaZlYzQnhOakZEUjJkSFRFdElXWE56VkZWbVluTTNObkpFY25jMWMzUkhaVUk1TWpsaVVrc3diMHRKWjBoTVNFY3hkeUo5ZlN3aVlYUmZhR0Z6YUNJNklrOHdaVVU0T0hSMkxYRnVUbHB3U0drNVUwTkJOa0VpZlEuUjRieXZ5LVNTRTQtbGFwbERfS0hKUGJFR0FMaDZDUU96dmhoSm03a1lUeWlVRXE3VFAxaDR4c3I5MjBwaVpnUVhENHYwbU44NXNkMlNpTjBFZHotOGRMY2JfQlJjSUJfNk1pTDFLdDRPSmxVdFU4Y3gwN3VSa1JNdnBoZXhIRk04UlRodC1BN2dYSDlRdlZoejBSVWk3b1hIOE1QVnFUYjBOcHdyZnlWUURhV2MtcmtHQ1JwamJlRWVqcTdpMTVZRFFNV2dBdzV6Y0hmYlZoTWc0czhDZjZaVFhXVnQ0Zmx6ZUZCUVlyUTJjUHJFeUxnRzJtMHlyWlRuOVZibHprQXlhRXQxMXlSYzc3Q1Foanotc0FvSmRKZm9lQzMtMVVXdTVMYUFhTHZocUFNeDlsbG50bEdhOWRxb1g1VEE3OEJYY1dPMWZkSk9BTTBFZGVLYzRIV2VnIiwidG9rZW5fdHlwZSI6InBvcCJ9.C2_3Bt3rB_jp7HQPazRlLYIg_cfmBV0gJvzEvn-S0TKvWo-j5_rc2CUL0he64Dl7l_f9jD6__8--FTPibOmzTSnZyHqWw4hRoJCtbxlhnZ0Pug4FsYgad8nxbWuVVS5pd43H2AciYighbRNm3k6ajEQiTRAJmugunoS823Ze41zL-HfnRRvFPSi1Mo_3iuo6efJaA4Vi9F-MF1m52-Mo2_UcbrFo-LRowDdD_Lh2Ax65_RQ68ZR7yGTQodQn1p-dmazLsBH7OWcQmtTUS7Kki80HYUwghyvsKHQVa0Db1Kzt1p8Q0Pt3oJAxOrzAz9YYmE8xP1uOIO1LNQwFyRuUkA
The PoP Token includes an id_token that has the JWK.
The Solid-Auth-Client PoPToken class (POPToken.js) returns the following JWT with 3 parts:
header: alg
payload:
iss: client_id
aud: resource server uri origin
id_token: id_token
token_type: 'pop'
exp:
iat:
key: session key
AuthenticationRequest.js:
static generateSessionKeys () {
return crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: { name: "SHA-256" },
},
true,
["sign", "verify"]
)
.then((keyPair) => {
// returns a keypair object
return Promise.all([
crypto.subtle.exportKey('jwk', keyPair.publicKey),
crypto.subtle.exportKey('jwk', keyPair.privateKey)
])
})
.then(jwkPair => {
let [ publicJwk, privateJwk ] = jwkPair
return { public: publicJwk, private: privateJwk }
})
}
RSASSA_PKCS1_v1_5.js
generateKey (params, extractable, usages) {
// 1. Verify usages
usages.forEach(usage => {
if (usage !== 'sign' && usage !== 'verify') {
throw new SyntaxError('Key usages can only include "sign" and "verify"')
}
})
let keypair = {}
// 2. Generate RSA keypair
try {
let {modulusLength,publicExponent} = params
// TODO
// - fallback on node-rsa if OpenSSL is not available on the system
let privateKey = spawnSync('openssl', ['genrsa', modulusLength || 4096]).stdout
let publicKey = spawnSync('openssl', ['rsa', '-pubout'], { input: privateKey }).stdout
try {
keypair.privateKey = privateKey.toString('ascii')
keypair.publicKey = publicKey.toString('ascii')
} catch (error){
throw new OperationError(error.message)
}
// 3. Throw operation error if anything fails
} catch (error) {
throw new OperationError(error.message)
}
// 4-9. Create and assign algorithm object
let algorithm = new RSASSA_PKCS1_v1_5(params)
// 10-13. Instantiate publicKey
let publicKey = new CryptoKey({
type: 'public',
algorithm,
extractable: true,
usages: ['verify'],
handle: keypair.publicKey
})
// 14-18. Instantiate privateKey
let privateKey = new CryptoKey({
type: 'private',
algorithm,
extractable: extractable,
usages: ['sign'],
handle: keypair.privateKey
})
// 19-22. Create and return a new keypair
return new CryptoKeyPair({publicKey,privateKey})
}
*/
import Foundation
class PoPToken: Codable {
}
| [
-1
] |
022898dab4a60c08fcfa6f9f77dd353e490c75af | 85e77e59904aed1dffc2dab999cda5c84f5723e5 | /ShoppingList/Item.swift | e4adcbe62847c50e269ee0bf40bb1463c16309e4 | [] | no_license | MrDee93/Shopping-List | 3fcfc0ad418cafd72d9cdaf7d497d31548de6501 | 5d5423f445ec6ca7072de5d6b31a86ec279b437d | refs/heads/master | 2020-03-19T00:49:57.800515 | 2018-06-07T15:04:23 | 2018-06-07T15:04:23 | 135,504,438 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,019 | swift | //
// Item.swift
// ShoppingList
//
// Created by Dayan Yonnatan on 23/06/2017.
// Copyright © 2017 Dayan Yonnatan. All rights reserved.
//
import Foundation
class Item {
var name:String?
var purchased:Bool? {
didSet {
self.dictionary?["purchased"] = self.purchased
}
}
var dictionary:Dictionary<String, Any>?
init(name:String, purchased:Bool) {
self.dictionary = Dictionary()
self.name = name
self.purchased = purchased
self.dictionary?["name"] = name
self.dictionary?["purchased"] = purchased
}
func setItemFrom(dictionary:Dictionary<String, Any>) {
if let thename = dictionary["name"] {
self.name = (thename as! String)
}
if let isitempurchased = dictionary["purchased"] {
self.purchased = (isitempurchased as! Bool)
}
}
func getDictionaryData() -> Dictionary<String
, Any> {
return self.dictionary!
}
}
| [
-1
] |
2d3c5ba5b066740cc1c316116900b8f571156772 | 19d4456efd7ffdf8289f455004d3a17dda6cb780 | /Sources/SwiftDiagramComponentsGenerator/astTypesExtensions/StatementsExtension.swift | 00cbe96c4f7c1f4ec14bd70cdc99cedd5dc5412a | [
"Apache-2.0",
"MIT"
] | permissive | gthr2000/swift-code-types-navigator | a7a79b5320f86e78dcf95cb027fa9b1d8784fdfa | 4ba9a4d599c2e3534f51465e05c8963ff3a275dd | refs/heads/master | 2020-03-08T01:41:20.114140 | 2018-03-16T16:16:39 | 2018-03-16T16:16:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 280 | swift | //
// StatementsExtension.swift
// SwiftDiagramComponentsGenerator
//
// Created by Jovan Jovanovski on 12/27/17.
//
import AST
extension Array where Element == Statement {
var declarations: [Declaration] {
return flatMap { $0 as? Declaration }
}
}
| [
-1
] |
3bf3dfc86b4451a856db5378af547da50bb1c367 | eea84abfd19defbee724c92fbc2ce96a284754fa | /SwiftHub/Modules/Search/SearchViewModel.swift | 9496918c7c7a3e79cba4ba20e0e5cecabb87dfa9 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | AnasAlmomany/SwiftHub | 08e608baba72c5986f1731b1cf5481fca5b64f40 | fb5e2d2330eff0fb65d164bb375a5e10da28782b | refs/heads/master | 2020-05-30T16:30:05.040725 | 2019-06-01T08:38:55 | 2019-06-01T08:38:55 | 189,846,614 | 1 | 0 | MIT | 2019-06-02T12:57:38 | 2019-06-02T12:57:38 | null | UTF-8 | Swift | false | false | 19,653 | swift | //
// SearchViewModel.swift
// SwiftHub
//
// Created by Khoren Markosyan on 6/30/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import RxDataSources
class SearchViewModel: ViewModel, ViewModelType {
struct Input {
let headerRefresh: Observable<Void>
let footerRefresh: Observable<Void>
let languageTrigger: Observable<Void>
let keywordTrigger: Driver<String>
let textDidBeginEditing: Driver<Void>
let languagesSelection: Observable<Void>
let searchTypeSegmentSelection: Observable<SearchTypeSegments>
let trendingPeriodSegmentSelection: Observable<TrendingPeriodSegments>
let searchModeSelection: Observable<SearchModeSegments>
let sortRepositorySelection: Observable<SortRepositoryItems>
let sortUserSelection: Observable<SortUserItems>
let selection: Driver<SearchSectionItem>
}
struct Output {
let items: BehaviorRelay<[SearchSection]>
let sortItems: Driver<[String]>
let sortText: Driver<String>
let totalCountText: Driver<String>
let textDidBeginEditing: Driver<Void>
let dismissKeyboard: Driver<Void>
let languagesSelection: Driver<LanguagesViewModel>
let repositorySelected: Driver<RepositoryViewModel>
let userSelected: Driver<UserViewModel>
let hidesTrendingPeriodSegment: Driver<Bool>
let hidesSearchModeSegment: Driver<Bool>
let hidesSortLabel: Driver<Bool>
}
let searchType = BehaviorRelay<SearchTypeSegments>(value: .repositories)
let trendingPeriod = BehaviorRelay<TrendingPeriodSegments>(value: .daily)
let searchMode = BehaviorRelay<SearchModeSegments>(value: .trending)
let keyword = BehaviorRelay(value: "")
let currentLanguage = BehaviorRelay<Language?>(value: Language.currentLanguage())
let sortRepositoryItem = BehaviorRelay(value: SortRepositoryItems.bestMatch)
let sortUserItem = BehaviorRelay(value: SortUserItems.bestMatch)
let repositorySearchElements = BehaviorRelay(value: RepositorySearch())
let userSearchElements = BehaviorRelay(value: UserSearch())
var repositoriesPage = 1
var usersPage = 1
func transform(input: Input) -> Output {
let elements = BehaviorRelay<[SearchSection]>(value: [])
let trendingRepositoryElements = BehaviorRelay<[TrendingRepository]>(value: [])
let trendingUserElements = BehaviorRelay<[TrendingUser]>(value: [])
let languageElements = BehaviorRelay<Languages?>(value: nil)
let repositorySelected = PublishSubject<Repository>()
let userSelected = PublishSubject<User>()
let dismissKeyboard = input.selection.mapToVoid()
input.searchTypeSegmentSelection.bind(to: searchType).disposed(by: rx.disposeBag)
input.trendingPeriodSegmentSelection.bind(to: trendingPeriod).disposed(by: rx.disposeBag)
input.searchModeSelection.bind(to: searchMode).disposed(by: rx.disposeBag)
input.keywordTrigger.skip(1).debounce(0.5).distinctUntilChanged().asObservable()
.bind(to: keyword).disposed(by: rx.disposeBag)
Observable.combineLatest(keyword, currentLanguage).map { keyword, currentLanguage in
return keyword.isEmpty && currentLanguage == nil ? .trending: .search
}.asObservable().bind(to: searchMode).disposed(by: rx.disposeBag)
input.sortRepositorySelection.bind(to: sortRepositoryItem).disposed(by: rx.disposeBag)
input.sortUserSelection.bind(to: sortUserItem).disposed(by: rx.disposeBag)
Observable.combineLatest(keyword, currentLanguage, sortRepositoryItem)
.filter({ (keyword, currentLanguage, sortRepositoryItem) -> Bool in
return keyword.isNotEmpty || currentLanguage != nil
})
.flatMapLatest({ [weak self] (keyword, currentLanguage, sortRepositoryItem) -> Observable<RxSwift.Event<RepositorySearch>> in
guard let self = self else { return Observable.just(RxSwift.Event.next(RepositorySearch())) }
self.repositoriesPage = 1
let query = self.makeQuery()
let sort = sortRepositoryItem.sortValue
let order = sortRepositoryItem.orderValue
return self.provider.searchRepositories(query: query, sort: sort, order: order, page: self.repositoriesPage, endCursor: nil)
.trackActivity(self.loading)
.trackActivity(self.headerLoading)
.trackError(self.error)
.materialize()
}).subscribe(onNext: { [weak self] (event) in
switch event {
case .next(let result):
self?.repositorySearchElements.accept(result)
default: break
}
}).disposed(by: rx.disposeBag)
input.footerRefresh.flatMapLatest({ [weak self] () -> Observable<RxSwift.Event<RepositorySearch>> in
guard let self = self else { return Observable.just(RxSwift.Event.next(RepositorySearch())) }
if self.searchMode.value != .search || !self.repositorySearchElements.value.hasNextPage {
var result = RepositorySearch()
result.totalCount = self.repositorySearchElements.value.totalCount
return Observable.just(RxSwift.Event.next(result))
.trackActivity(self.footerLoading) // for force stoping table footer animation
}
self.repositoriesPage += 1
let query = self.makeQuery()
let sort = self.sortRepositoryItem.value.sortValue
let order = self.sortRepositoryItem.value.orderValue
let endCursor = self.repositorySearchElements.value.endCursor
return self.provider.searchRepositories(query: query, sort: sort, order: order, page: self.repositoriesPage, endCursor: endCursor)
.trackActivity(self.loading)
.trackActivity(self.footerLoading)
.trackError(self.error)
.materialize()
}).subscribe(onNext: { [weak self] (event) in
switch event {
case .next(let result):
var newResult = result
newResult.items = (self?.repositorySearchElements.value.items ?? []) + result.items
self?.repositorySearchElements.accept(newResult)
default: break
}
}).disposed(by: rx.disposeBag)
Observable.combineLatest(keyword, currentLanguage, sortUserItem)
.filter({ (keyword, currentLanguage, sortRepositoryItem) -> Bool in
return keyword.isNotEmpty || currentLanguage != nil
})
.flatMapLatest({ [weak self] (keyword, currentLanguage, sortUserItem) -> Observable<RxSwift.Event<UserSearch>> in
guard let self = self else { return Observable.just(RxSwift.Event.next(UserSearch())) }
self.usersPage = 1
let query = self.makeQuery()
let sort = sortUserItem.sortValue
let order = sortUserItem.orderValue
return self.provider.searchUsers(query: query, sort: sort, order: order, page: self.usersPage, endCursor: nil)
.trackActivity(self.loading)
.trackActivity(self.headerLoading)
.trackError(self.error)
.materialize()
}).subscribe(onNext: { [weak self] (event) in
switch event {
case .next(let result):
self?.userSearchElements.accept(result)
default: break
}
}).disposed(by: rx.disposeBag)
input.footerRefresh.flatMapLatest({ [weak self] () -> Observable<RxSwift.Event<UserSearch>> in
guard let self = self else { return Observable.just(RxSwift.Event.next(UserSearch())) }
if self.searchMode.value != .search || !self.userSearchElements.value.hasNextPage {
var result = UserSearch()
result.totalCount = self.userSearchElements.value.totalCount
return Observable.just(RxSwift.Event.next(UserSearch()))
}
self.usersPage += 1
let query = self.makeQuery()
let sort = self.sortUserItem.value.sortValue
let order = self.sortUserItem.value.orderValue
let endCursor = self.userSearchElements.value.endCursor
return self.provider.searchUsers(query: query, sort: sort, order: order, page: self.usersPage, endCursor: endCursor)
.trackActivity(self.loading)
.trackActivity(self.footerLoading)
.trackError(self.error)
.materialize()
}).subscribe(onNext: { [weak self] (event) in
switch event {
case .next(let result):
var newResult = result
newResult.items = (self?.userSearchElements.value.items ?? []) + result.items
self?.userSearchElements.accept(newResult)
default: break
}
}).disposed(by: rx.disposeBag)
keyword.asDriver().debounce(3.0).filterEmpty().drive(onNext: { (keyword) in
analytics.log(.search(keyword: keyword))
}).disposed(by: rx.disposeBag)
Observable.just(()).flatMapLatest { () -> Observable<Languages> in
return self.provider.languages()
.trackActivity(self.loading)
.trackError(self.error)
}.subscribe(onNext: { (item) in
languageElements.accept(item)
}).disposed(by: rx.disposeBag)
let trendingPeriodSegment = BehaviorRelay(value: TrendingPeriodSegments.daily)
input.trendingPeriodSegmentSelection.bind(to: trendingPeriodSegment).disposed(by: rx.disposeBag)
let trendingTrigger = Observable.of(input.headerRefresh.skip(1),
input.trendingPeriodSegmentSelection.mapToVoid().skip(1),
currentLanguage.mapToVoid().skip(1),
keyword.asObservable().map { $0.isEmpty }.filter { $0 == true }.mapToVoid()).merge()
trendingTrigger.flatMapLatest { () -> Observable<RxSwift.Event<[TrendingRepository]>> in
let language = self.currentLanguage.value?.urlParam ?? ""
let since = trendingPeriodSegment.value.paramValue
return self.provider.trendingRepositories(language: language, since: since)
.trackActivity(self.loading)
.trackActivity(self.headerLoading)
.trackError(self.error)
.materialize()
}.subscribe(onNext: { (event) in
switch event {
case .next(let items): trendingRepositoryElements.accept(items)
default: break
}
}).disposed(by: rx.disposeBag)
trendingTrigger.flatMapLatest { () -> Observable<RxSwift.Event<[TrendingUser]>> in
let language = self.currentLanguage.value?.urlParam ?? ""
let since = trendingPeriodSegment.value.paramValue
return self.provider.trendingDevelopers(language: language, since: since)
.trackActivity(self.loading)
.trackActivity(self.headerLoading)
.trackError(self.error)
.materialize()
}.subscribe(onNext: { (event) in
switch event {
case .next(let items): trendingUserElements.accept(items)
default: break
}
}).disposed(by: rx.disposeBag)
input.selection.drive(onNext: { (item) in
switch item {
case .trendingRepositoriesItem(let cellViewModel):
repositorySelected.onNext(Repository(repo: cellViewModel.repository))
case .trendingUsersItem(let cellViewModel):
userSelected.onNext(User(user: cellViewModel.user))
case .repositoriesItem(let cellViewModel):
repositorySelected.onNext(cellViewModel.repository)
case .usersItem(let cellViewModel):
userSelected.onNext(cellViewModel.user)
}
}).disposed(by: rx.disposeBag)
Observable.combineLatest(trendingRepositoryElements, trendingUserElements, repositorySearchElements, userSearchElements, searchType, searchMode)
.map { (trendingRepositories, trendingUsers, repositories, users, searchType, searchMode) -> [SearchSection] in
var elements: [SearchSection] = []
let language = self.currentLanguage.value?.displayName()
let since = trendingPeriodSegment.value
var title = ""
switch searchMode {
case .trending: title = language != nil ?
R.string.localizable.searchTrendingSectionWithLanguageTitle.key.localizedFormat("\(language ?? "")") :
R.string.localizable.searchTrendingSectionTitle.key.localized()
case .search: title = language != nil ?
R.string.localizable.searchSearchSectionWithLanguageTitle.key.localizedFormat("\(language ?? "")") :
R.string.localizable.searchSearchSectionTitle.key.localized()
}
switch searchType {
case .repositories:
switch searchMode {
case .trending:
let repositories = trendingRepositories.map({ (repository) -> SearchSectionItem in
let cellViewModel = TrendingRepositoryCellViewModel(with: repository, since: since)
return SearchSectionItem.trendingRepositoriesItem(cellViewModel: cellViewModel)
})
if repositories.isNotEmpty {
elements.append(SearchSection.repositories(title: title, items: repositories))
}
case .search:
let repositories = repositories.items.map({ (repository) -> SearchSectionItem in
let cellViewModel = RepositoryCellViewModel(with: repository)
return SearchSectionItem.repositoriesItem(cellViewModel: cellViewModel)
})
if repositories.isNotEmpty {
elements.append(SearchSection.repositories(title: title, items: repositories))
}
}
case .users:
switch searchMode {
case .trending:
let users = trendingUsers.map({ (user) -> SearchSectionItem in
let cellViewModel = TrendingUserCellViewModel(with: user)
return SearchSectionItem.trendingUsersItem(cellViewModel: cellViewModel)
})
if users.isNotEmpty {
elements.append(SearchSection.users(title: title, items: users))
}
case .search:
let users = users.items.map({ (user) -> SearchSectionItem in
let cellViewModel = UserCellViewModel(with: user)
return SearchSectionItem.usersItem(cellViewModel: cellViewModel)
})
if users.isNotEmpty {
elements.append(SearchSection.users(title: title, items: users))
}
}
}
return elements
}.bind(to: elements).disposed(by: rx.disposeBag)
let textDidBeginEditing = input.textDidBeginEditing
let repositoryDetails = repositorySelected.map({ (repository) -> RepositoryViewModel in
let viewModel = RepositoryViewModel(repository: repository, provider: self.provider)
return viewModel
}).asDriverOnErrorJustComplete()
let userDetails = userSelected.map({ (user) -> UserViewModel in
let viewModel = UserViewModel(user: user, provider: self.provider)
return viewModel
}).asDriverOnErrorJustComplete()
let languagesSelection = input.languagesSelection.asDriver(onErrorJustReturn: ()).map { () -> LanguagesViewModel in
let viewModel = LanguagesViewModel(currentLanguage: self.currentLanguage.value, languages: languageElements.value, provider: self.provider)
viewModel.currentLanguage.skip(1).bind(to: self.currentLanguage).disposed(by: self.rx.disposeBag)
return viewModel
}
let hidesTrendingPeriodSegment = searchMode.map { $0 != .trending }.asDriver(onErrorJustReturn: false)
let hidesSearchModeSegment = Observable.combineLatest(input.keywordTrigger.asObservable().map { $0.isNotEmpty }, currentLanguage.map { $0 == nil })
.map { $0 || $1 }.asDriver(onErrorJustReturn: false)
let hidesSortLabel = searchMode.map { $0 == .trending }.asDriver(onErrorJustReturn: false)
let sortItems = Observable.combineLatest(searchType, input.languageTrigger)
.map { (searchType, _) -> [String] in
switch searchType {
case .repositories: return SortRepositoryItems.allItems()
case .users: return SortUserItems.allItems()
}
}.asDriver(onErrorJustReturn: [])
let sortText = Observable.combineLatest(searchType, sortRepositoryItem, sortUserItem, input.languageTrigger)
.map { (searchType, sortRepositoryItem, sortUserItem, _) -> String in
switch searchType {
case .repositories: return sortRepositoryItem.title + " ▼"
case .users: return sortUserItem.title + " ▼"
}
}.asDriver(onErrorJustReturn: "")
let totalCountText = Observable.combineLatest(searchType, repositorySearchElements, userSearchElements, input.languageTrigger)
.map { (searchType, repositorySearchElements, userSearchElements, _) -> String in
switch searchType {
case .repositories: return R.string.localizable.searchRepositoriesTotalCountTitle.key.localizedFormat("\(repositorySearchElements.totalCount.kFormatted())")
case .users: return R.string.localizable.searchUsersTotalCountTitle.key.localizedFormat("\(userSearchElements.totalCount.kFormatted())")
}
}.asDriver(onErrorJustReturn: "")
return Output(items: elements,
sortItems: sortItems,
sortText: sortText,
totalCountText: totalCountText,
textDidBeginEditing: textDidBeginEditing,
dismissKeyboard: dismissKeyboard,
languagesSelection: languagesSelection,
repositorySelected: repositoryDetails,
userSelected: userDetails,
hidesTrendingPeriodSegment: hidesTrendingPeriodSegment,
hidesSearchModeSegment: hidesSearchModeSegment,
hidesSortLabel: hidesSortLabel)
}
func makeQuery() -> String {
var query = keyword.value
if let language = currentLanguage.value?.urlParam {
query += " language:\(language)"
}
return query
}
}
| [
-1
] |
c976eb80bc50a0ef1a8a5eb23beb2d95ce3a3641 | e9fe8aa337e033ca64556e98277afd36ef3a6c39 | /MusicPlayer/ViewController.swift | 8c8885d416d9cf041dfe1427b9f1261557aca2c3 | [] | no_license | lucaswkuipers/MusicPlayer | e4cf61df55ba720e2afdb034f1814c04d1b17589 | 10ea831e2958fd2d5c901ae1b99c30ec492b7f30 | refs/heads/main | 2023-04-17T19:19:57.118641 | 2021-04-30T06:02:46 | 2021-04-30T06:02:46 | 363,042,053 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 377 | swift | //
// ViewController.swift
// MusicPlayer
//
// Created by Lucas Werner Kuipers on 24/03/2021.
// Copyright © 2021 Lucas Werner Kuipers. 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.
}
}
| [
190120
] |
7ff8d63512ff61fcd5b5d589f34130e2a4468d12 | 8e1b3028df61af2317d3317e8a2f046a83640fd6 | /Example/Tests/Tests.swift | 5e3a6a25dfc3f5e211316b6f04ac47f74a8db0bd | [
"MIT"
] | permissive | TENQUBE/VisualFramework | 2eb639e714c19dcabd2a100f2f8a12a9f07100fb | e406df9de833453be6966cf1182f559a0388ba73 | refs/heads/master | 2020-04-26T16:39:59.014155 | 2019-03-04T07:07:09 | 2019-03-04T07:07:09 | 173,651,971 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 752 | swift | import XCTest
import VisualFramework
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| [
305179,
278558,
307231,
313375,
102437,
227370,
360491,
276533,
276534,
159807,
286788,
280649,
223316,
315476,
223318,
288857,
227417,
278618,
194656,
309345,
227428,
276582,
276589,
278638,
227439,
276592,
131189,
223350,
292992,
141450,
311435,
215178,
311438,
276627,
276631,
276632,
227492,
196773,
129203,
299187,
131256,
280762,
223419,
299198,
309444,
276682,
276687,
280802,
276715,
233715,
157944,
211193,
168188,
276753,
276760,
309529,
278810,
299293,
282919,
262450,
276792,
315706,
311621,
280902,
278856,
227658,
276813,
6481,
6482,
6489,
323935,
276835,
321894,
416104,
276847,
285040,
280961,
227725,
178578,
190871,
293274,
61857,
61859,
278961,
278965,
293303,
276920,
33211,
276925,
278978,
111056,
278993,
287198,
227809,
358882,
227813,
279013,
279022,
281072,
279039,
276998,
287241,
279050,
186893,
303631,
223767,
223769,
277017,
291358,
293419,
277048,
277049,
301634,
277066,
295519,
66150,
277094,
277101,
287346,
277111,
279164,
277117,
291454,
184962,
303746,
152203,
225933,
277133,
133774,
277141,
225944,
230040,
164512,
285353,
205487,
285361,
303793,
299699,
293556,
342706,
166580,
285371,
199366,
225997,
226004,
203477,
279252,
226007,
277204,
119513,
363231,
226019,
285415,
342762,
277227,
230134,
234234,
279294,
234241,
209670,
226058,
234250,
234253,
234263,
369432,
234268,
234277,
279336,
289576,
277289,
234283,
234286,
234289,
234294,
230199,
162621,
234301,
289598,
281408,
293693,
162626,
277316,
234311,
234312,
299849,
234317,
277325,
293711,
277327,
234323,
234326,
234331,
277339,
301918,
297822,
279392,
349026,
297826,
234340,
174949,
234343,
234346,
234355,
277366,
234360,
279417,
209785,
177019,
234361,
277370,
234366,
234367,
226170,
158593,
234372,
226181,
113542,
213894,
226184,
277381,
228234,
226189,
295824,
234386,
234387,
234392,
324507,
279456,
234400,
277410,
234404,
289703,
234409,
275371,
236461,
226222,
234419,
226227,
234425,
234427,
277435,
287677,
234430,
234436,
234438,
52172,
234444,
234445,
183248,
234451,
234454,
234457,
234463,
234466,
277479,
234472,
234473,
234477,
234482,
287731,
277492,
314355,
234498,
234500,
277509,
277510,
230410,
234506,
295953,
277523,
230423,
197657,
281625,
281626,
175132,
234531,
234534,
310317,
234542,
234548,
234555,
238651,
277563,
230463,
234560,
207938,
234565,
234569,
300111,
234577,
296018,
296019,
234583,
234584,
230499,
281700,
300135,
275565,
156785,
312434,
275571,
300150,
300151,
234616,
398457,
234622,
300158,
285828,
302213,
253063,
234632,
275591,
234642,
277651,
308372,
119963,
234656,
330913,
306338,
234659,
277665,
234663,
275625,
300201,
275628,
238769,
226481,
208058,
277690,
230588,
283840,
279747,
279760,
290000,
189652,
203989,
363744,
195811,
298212,
304356,
285929,
279792,
298228,
204022,
234742,
228600,
208124,
292107,
277792,
339234,
199971,
259363,
304421,
277800,
113966,
226608,
277814,
300343,
226624,
15686,
226632,
294218,
177484,
222541,
277838,
296273,
314709,
283991,
357719,
218462,
224606,
142689,
230756,
163175,
281962,
173420,
284014,
279919,
181625,
142716,
277890,
226694,
281992,
277900,
230799,
112017,
306579,
206228,
226712,
310692,
279974,
282024,
370091,
277939,
279989,
296375,
277943,
277952,
296387,
415171,
163269,
277957,
296391,
300487,
280013,
312782,
284116,
226781,
277988,
310757,
316902,
277993,
277994,
296425,
278005,
306677,
300542,
306693,
192010,
149007,
65041,
282136,
204313,
278056,
278060,
286254,
194110,
276040,
366154,
276045,
286288,
276050,
280147,
300630,
243292,
147036,
298590,
370271,
282213,
317032,
222832,
276084,
276085,
188031,
192131,
229001,
310923,
312972,
282259,
276120,
278170,
280220,
276126,
282273,
276129,
282276,
278191,
198324,
286388,
296628,
278214,
276173,
302797,
212688,
9936,
302802,
9937,
286423,
216795,
276195,
153319,
313065,
280300,
419569,
276210,
276219,
194303,
288512,
311042,
288516,
278285,
276238,
294678,
284442,
278299,
276253,
288547,
159533,
165677,
276282,
276283,
276287,
345919,
276294,
282438,
276298,
216918,
307031,
276318,
237408,
282474,
288619,
276344,
194429,
255872,
1923,
40850,
40853,
44952,
247712,
294823,
276394,
276401,
276408,
290746,
276421,
276422,
276430,
231375,
153554,
276444,
280541,
276454,
276459,
296941
] |
736d018b6f37ed9e32d8ce854f2365830027fe34 | ccf204ee620894c1000f5b0f1f5c6b9427661a22 | /trice/ViewControllers/BookmarkController.swift | 50b2248d9552d8548cb7baf7911125ce2b7ab4f6 | [] | no_license | Corentinfardeau/trice | d6ebb0323a47ae2f8383a6584100a60a8c966237 | dd158c15e92f3d9572f18b9fb2872a8dff4d8663 | refs/heads/master | 2021-01-10T17:39:33.187431 | 2015-12-17T22:48:15 | 2015-12-17T22:48:15 | 47,973,782 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 6,428 | swift | //
// BookmarkController.swift
// trice
//
// Created by Gabriel Vergnaud on 15/12/2015.
// Copyright © 2015 Corentin FARDEAU. All rights reserved.
//
import UIKit
import Parse
import PKHUD
class BookmarkController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var likes: [PFObject]?
@IBOutlet weak var bookmarkTableView: UITableView!
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var backgroungTitle: UILabel!
@IBOutlet weak var backgroundInfos: UITextView!
@IBOutlet weak var backgroundButton: UIButton!
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
return refreshControl
}()
override func viewDidLoad() {
super.viewDidLoad()
bookmarkTableView.tableFooterView = UIView()
bookmarkTableView.addSubview(refreshControl)
getLikes()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
getLikes()
}
func getLikes() {
Api.sharedInstance.getLikes(
{ likes in
self.likes = likes
if(self.likes?.count == 0){
self.manageBackground(true)
}else{
self.bookmarkTableView.reloadData()
self.manageBackground(false)
}
},
errorCallback: { error in
switch error.code {
case 100:
self.showAlert("Oups", message: "No Internet connection ;(")
break
default:
break
}
}
)
}
func manageBackground(visible:Bool){
if(visible){
backgroundButton.hidden = false
backgroundImage.hidden = false
backgroundInfos.hidden = false
backgroungTitle.hidden = false
}else{
backgroundButton.hidden = true
backgroundImage.hidden = true
backgroundInfos.hidden = true
backgroungTitle.hidden = true
}
}
@IBAction func seePostAction(sender: AnyObject) {
tabBarController?.selectedIndex = 0
}
// MARK: - TableView DataSource
func handleRefresh(refreshControl: UIRefreshControl) {
getLikes()
self.bookmarkTableView.reloadData()
refreshControl.endRefreshing()
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) ->
[UITableViewRowAction]? {
let addTime = UITableViewRowAction(style: .Default, title: "Delete") {_,_ in
if let likes = self.likes {
self.showDeleteAlert(likes[indexPath.row])
}
}
return [addTime]
}
func tableView(bookmarkTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let likes = self.likes {
return likes.count
}else{
return 0
}
}
func tableView(bookmarkTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = bookmarkTableView.dequeueReusableCellWithIdentifier(BookmarkTableViewCell.identifier, forIndexPath: indexPath) as! BookmarkTableViewCell
if let likes = self.likes {
cell.setLike(likes[indexPath.row])
}
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let likes = likes {
let like = likes[indexPath.row]
let url = NSURL(string: like["link"] as! String)!
UIApplication.sharedApplication().openURL(url)
}
bookmarkTableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: - Alert
func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func showDeleteAlert(post: PFObject) {
let alert = UIAlertController(title: "Wait a second ...", message: "Are you sure you want to delete this link ?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: nil))
alert.addAction(UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: { (action: UIAlertAction) -> () in
Api.sharedInstance.deleteLike(post,
successCallback: { likes in
self.likes = likes
self.bookmarkTableView.reloadData()
PKHUD.sharedHUD.contentView = PKHUDSuccessView()
PKHUD.sharedHUD.show()
PKHUD.sharedHUD.hide(afterDelay: 0.8);
},
errorCallback: { error in
self.showAlert("Oups", message: "Couldn't delete this link.")
}
)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
| [
-1
] |
4c9986e8106d2b63cf2b6aad2467d6b6179218f7 | 6e07c6c53dc5c1c204db7e689fb4c841d49bccd9 | /SimpleMapExample/SimpleMapExample/Services/ImageCache.swift | 029767173e7262c587fe474c9383c65fa9b43bc6 | [
"MIT"
] | permissive | AntiPavel/SimpleMapExample | 2fb6ad7222393ab86a8dd22734161cb4a6658a23 | 0112e99845359fbbb8dbccf113dc390daa73f4d7 | refs/heads/master | 2020-07-03T12:45:31.490076 | 2019-08-19T21:18:50 | 2019-08-19T21:18:50 | 201,908,561 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,055 | swift | //
// ImageCache.swift
// SimpleMapExample
//
// Created by paul on 12/08/2019.
// Copyright © 2019 pavel. All rights reserved.
//
import Foundation
import UIKit
var imageCache: ImageCache = ImageCache()
final class ImageCache: NSCache<NSString, UIImage> {
required override init() {
super.init()
totalCostLimit = totalCostLimit()
NotificationCenter.default.addObserver(self,
selector: #selector(clearCache),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
}
@objc private func clearCache() {
removeAllObjects()
}
private func totalCostLimit() -> Int {
let physicalMemory = ProcessInfo.processInfo.physicalMemory
let ratio = physicalMemory <= (1024 * 1024 * 512) ? 0.05 : 0.1
let limit = physicalMemory / UInt64(1 / ratio)
return limit > UInt64(Int.max) ? Int.max : Int(limit)
}
}
| [
-1
] |
02ea18da986d668fd3a9be1e8ad991e93d664e1e | 90f4b04bfc776c3290bad931705a6bc555d6d723 | /qzhApp/Classes/View/searchViewController/CustomQZHCell.swift | 508108e081744685f10d86adca09fc200458b604 | [] | no_license | wangruiyuan-wry/qzhApp | 2c0eabd24f33b42b5f851ca6cb085a659a252510 | d4d2588c6bab1ebd547f39bcbc1591a2d02be118 | refs/heads/master | 2021-09-15T02:17:29.397400 | 2018-05-24T08:01:37 | 2018-05-24T08:01:37 | 115,596,594 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,142 | swift | //
// CustomQZHCell.swift
// qzhApp
//
// Created by sbxmac on 2018/4/20.
// Copyright © 2018年 SpecialTech. All rights reserved.
//
import UIKit
class CustomQZHCell: UITableViewCell {
@IBOutlet weak var title: QZHUILabelView!
@IBOutlet weak var selectText: QZHUILabelView!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var ListArray: QZHUIView!
@IBOutlet weak var allList: QZHUIView!
var open:QZHUIView = QZHUIView()
var cellHeight:CGFloat = 0
var listHeight:CGFloat = 0
override func awakeFromNib() {
super.awakeFromNib()
title.setLabelView(0, 20*PX, 120*PX, 33*PX, NSTextAlignment.left, UIColor.clear, myColor().Gray6(), 24, "")
selectText.setLabelView(400*PX, 20*PX, 109*PX, 33*PX, NSTextAlignment.right, UIColor.clear, myColor().blue007aff(), 24, "")
selectText.numberOfLines = 1
selectText.lineBreakMode = .byTruncatingTail
icon.frame = CGRect(x:529*PX,y:26*PX,width:27*PX,height:17*PX)
icon.image = UIImage(named:"closeIcon")
open.setupViews(x: 400*PX, y: 0, width: 200*PX, height: 53*PX, bgColor: UIColor.clear)
self.addSubview(open)
allList.isHidden = true
allList.setupViews(x: 0, y: 53*PX, width: 560*PX, height: 199*PX, bgColor: UIColor.clear)
ListArray.setupViews(x: 0, y: 53*PX, width: 560*PX, height: 199*PX, bgColor: UIColor.clear)
ListArray.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setupList(x:CGFloat,y:CGFloat,title:String,id:Int,sel:Bool)->[String:CGFloat]{
let btn:QZHUILabelView = QZHUILabelView()
btn.layer.cornerRadius = 8*PX
btn.layer.masksToBounds = true
btn.setLabelView(x, y, 173*PX, 60*PX, NSTextAlignment.center, myColor().GrayF1F2F6(), myColor().Gray6(), 24, title)
btn.layer.borderColor = myColor().GrayF1F2F6().cgColor
btn.layer.borderWidth = 1*PX
btn.tag = id
btn.addOnClickLister(target: self, action: #selector(self.click(_:)))
ListArray.addSubview(btn)
if listHeight > 199*PX{
ListArray.height = listHeight
}
if sel{
btn.layer.borderColor = myColor().blue007aff().cgColor
btn.layer.borderWidth = 1*PX
btn.restorationIdentifier = "sel"
btn.textColor = myColor().blue007aff()
btn.backgroundColor = UIColor.white
}
// allList.addSubview(btn)
let dic:[String:CGFloat] = ["x":x+192*PX,"y":y]
listHeight = y+80*PX
cellHeight = listHeight + 53*PX
return dic
}
func click(_ sender:UITapGestureRecognizer){
let _this:QZHUILabelView = sender.view as! QZHUILabelView
if _this.restorationIdentifier == "sel"{
_this.restorationIdentifier = ""
_this.backgroundColor = myColor().GrayF1F2F6()
_this.textColor = myColor().Gray6()
_this.layer.borderColor = myColor().GrayF1F2F6().cgColor
}else{
_this.restorationIdentifier = "sel"
_this.backgroundColor = UIColor.white
_this.textColor = myColor().blue007aff()
_this.layer.borderColor = myColor().blue007aff().cgColor
}
selectText.text = ""
selectText.restorationIdentifier = ""
let children:[QZHUILabelView] = self.ListArray.subviews as! [QZHUILabelView]
for child in children{
if child.restorationIdentifier == "sel"{
if selectText.text != ""{
selectText.text = "\(selectText.text!),\(child.text!)"
selectText.restorationIdentifier = "\(selectText.restorationIdentifier!),\(child.tag)"
}else{
selectText.text = "\(child.text!)"
selectText.restorationIdentifier = "\(child.tag)"
}
}
}
}
}
| [
-1
] |
33e7fd88d15e684158b4994579d5ae52bc34ed10 | 3d0b5617d0bc27aec1c861e5b6cb928985f8ea21 | /CoderFriends/AppDelegate.swift | 6e9d6759168b586542b62af87ef1915650c36501 | [] | no_license | vigneshios/Networking-WithCodableProtocols | 2ef40ae3d8fb7ab50a161544b3afa3b31c6bd5a0 | c3a7ea6651de24a7d432a5427e335702564e35ed | refs/heads/master | 2021-07-17T09:17:44.600041 | 2020-05-31T18:21:27 | 2020-05-31T18:21:27 | 168,920,587 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,168 | swift | //
// AppDelegate.swift
// CoderFriends
//
// Created by Apple on 03/02/19.
// Copyright © 2019 Vignesh. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| [
229380,
229383,
229385,
294924,
229388,
278542,
327695,
229391,
278545,
229394,
278548,
229397,
229399,
229402,
278556,
229405,
278559,
229408,
294950,
229415,
229417,
327722,
237613,
229422,
360496,
237618,
229426,
229428,
286774,
286776,
319544,
286778,
229432,
204856,
352318,
286791,
237640,
286797,
278605,
311375,
163920,
237646,
196692,
319573,
311383,
319590,
311400,
278635,
303212,
278639,
131192,
278648,
237693,
303230,
327814,
303241,
131209,
303244,
311436,
319633,
286873,
286876,
311460,
311469,
32944,
327862,
286906,
327866,
180413,
286910,
131264,
286916,
286922,
286924,
286926,
319694,
131281,
278743,
278747,
295133,
155872,
319716,
237807,
303345,
286962,
303347,
131314,
229622,
327930,
278781,
278783,
278785,
237826,
319751,
278792,
286987,
319757,
311569,
286999,
319770,
287003,
287006,
287009,
287012,
287014,
287016,
287019,
311598,
287023,
262448,
311601,
287032,
155966,
319809,
319810,
278849,
319814,
311623,
319818,
311628,
229709,
319822,
287054,
278865,
229717,
196963,
196969,
139638,
213367,
106872,
319872,
311683,
311693,
65943,
319898,
311719,
278952,
139689,
278957,
311728,
278967,
180668,
311741,
278975,
319938,
98756,
278980,
278983,
319945,
278986,
319947,
278990,
278994,
279003,
279006,
188895,
172512,
287202,
279010,
279015,
172520,
319978,
279020,
172526,
311791,
279023,
172529,
279027,
319989,
172534,
180727,
164343,
311804,
287230,
279040,
303617,
287234,
279045,
172550,
303623,
172552,
320007,
287238,
279051,
172558,
279055,
303632,
279058,
303637,
279063,
279067,
172572,
279072,
172577,
295459,
172581,
295461,
279082,
311850,
279084,
172591,
172598,
279095,
172607,
172609,
172612,
377413,
172614,
213575,
172618,
303690,
33357,
287309,
303696,
279124,
172634,
262752,
254563,
172644,
311911,
189034,
295533,
189039,
172656,
352880,
295538,
172655,
172660,
287349,
189044,
287355,
287360,
295553,
172675,
295557,
287365,
311942,
303751,
352905,
311946,
287371,
279178,
311951,
287377,
172691,
287381,
311957,
221850,
287386,
230045,
172702,
287390,
164509,
172705,
287394,
172707,
303780,
303773,
287398,
287400,
279208,
172714,
295595,
279212,
189102,
172721,
287409,
66227,
303797,
189114,
287419,
303804,
328381,
287423,
328384,
172737,
279231,
287427,
312006,
172748,
287436,
107212,
172751,
287440,
295633,
172755,
303827,
279255,
172760,
287450,
303835,
279258,
189149,
303838,
213724,
312035,
279267,
295654,
279272,
230128,
312048,
312050,
230131,
189169,
205564,
303871,
230146,
328453,
295685,
230154,
33548,
312077,
295695,
295701,
230169,
369433,
295707,
328476,
295710,
230175,
295720,
303914,
279340,
205613,
279353,
230202,
312124,
328508,
222018,
295755,
377676,
148302,
287569,
230237,
230241,
279394,
303976,
336744,
303981,
303985,
303987,
328563,
279413,
303991,
303997,
295806,
295808,
295813,
304005,
320391,
304007,
304009,
213895,
304011,
230284,
304013,
295822,
189325,
279438,
189329,
295825,
304019,
189331,
58262,
304023,
304027,
279452,
410526,
279461,
304042,
213931,
230327,
304055,
287675,
197564,
230334,
304063,
304065,
213954,
295873,
156612,
189378,
213963,
197580,
312272,
304084,
304090,
320481,
304106,
320490,
312302,
328687,
320496,
304114,
295928,
320505,
312321,
295945,
230413,
197645,
295949,
320528,
140312,
295961,
238620,
197663,
304164,
304170,
304175,
238641,
312374,
238652,
238655,
230465,
238658,
336964,
296004,
205895,
320584,
238666,
296021,
402518,
336987,
230497,
296036,
296040,
361576,
205931,
164973,
279661,
312432,
279669,
337018,
66690,
279683,
222340,
205968,
296084,
238745,
304285,
238756,
205991,
222377,
165035,
337067,
238766,
165038,
230576,
238770,
304311,
230592,
312518,
279750,
230600,
230607,
148690,
320727,
279769,
304348,
279777,
304354,
296163,
320740,
279781,
304360,
320748,
279788,
279790,
304370,
296189,
320771,
312585,
296202,
296205,
230674,
320786,
230677,
296213,
230679,
320792,
230681,
296215,
214294,
230689,
173350,
312622,
296243,
312630,
222522,
296253,
230718,
296255,
312639,
296259,
378181,
296262,
230727,
238919,
296264,
320840,
296267,
296271,
222545,
230739,
312663,
222556,
337244,
230752,
312676,
230760,
173418,
148843,
410987,
230763,
230768,
296305,
312692,
230773,
304505,
304506,
181626,
181631,
312711,
312712,
296331,
288140,
288144,
230800,
304533,
288154,
337306,
288160,
288162,
288164,
279975,
304555,
370092,
279983,
173488,
288176,
312755,
296373,
312759,
279991,
288185,
337335,
222652,
312766,
173507,
296389,
222665,
230860,
312783,
288208,
230865,
288210,
370130,
222676,
288212,
288214,
148946,
239064,
329177,
288218,
280021,
288220,
288217,
239070,
288224,
288226,
370146,
280034,
288229,
280038,
288230,
288232,
320998,
280036,
288234,
288236,
288238,
288240,
288242,
296435,
288244,
288250,
296446,
321022,
402942,
148990,
296450,
206336,
230916,
230919,
214535,
230923,
304651,
304653,
402969,
230940,
222752,
108066,
296486,
296488,
157229,
230961,
157236,
288320,
288325,
124489,
280140,
280145,
288338,
280149,
280152,
288344,
239194,
181854,
403039,
280158,
370272,
239202,
370279,
312938,
280183,
280185,
280188,
280191,
116354,
280194,
280208,
280211,
288408,
280218,
280222,
419489,
190118,
321195,
296622,
321200,
337585,
296626,
296634,
296637,
419522,
313027,
280260,
419525,
206536,
280264,
206539,
206541,
206543,
263888,
313044,
280276,
321239,
280283,
313052,
288478,
313055,
419555,
321252,
313066,
288494,
280302,
280304,
313073,
321266,
288499,
419570,
288502,
280314,
288510,
124671,
67330,
280324,
198405,
288519,
198416,
280337,
296723,
116503,
321304,
329498,
296731,
321311,
313121,
313123,
304932,
321316,
280363,
141101,
165678,
321336,
296767,
288576,
345921,
337732,
304968,
280393,
280402,
173907,
313171,
313176,
280419,
321381,
296812,
313201,
1920,
255873,
305028,
280454,
247688,
280464,
124817,
280468,
239510,
280473,
124827,
214940,
247709,
214944,
280487,
313258,
321458,
296883,
124853,
214966,
296890,
10170,
288700,
296894,
190403,
296900,
280515,
337862,
165831,
280521,
231379,
296921,
354265,
354270,
239586,
313320,
354281,
231404,
124913,
165876,
321528,
239612,
313340,
288764,
239617,
313347,
288773,
313358,
305176,
321560,
313371,
354338,
305191,
223273,
313386,
354348,
124978,
215090,
124980,
288824,
288826,
321595,
313406,
288831,
288836,
67654,
280651,
354382,
288848,
280658,
215123,
354390,
288855,
288859,
280669,
313438,
149599,
280671,
149601,
321634,
149603,
223327,
329830,
280681,
313451,
223341,
280687,
149618,
215154,
313458,
280691,
313464,
329850,
321659,
280702,
288895,
321670,
215175,
141446,
141455,
141459,
275606,
280725,
313498,
100520,
288936,
280747,
288940,
288947,
321717,
280759,
280764,
280769,
280771,
280774,
313548,
321740,
280783,
280786,
313557,
280793,
280796,
338147,
280804,
280807,
157930,
280811,
280817,
125171,
157940,
182517,
280825,
280827,
280830,
280831,
125187,
280835,
125191,
125207,
125209,
321817,
125218,
321842,
223539,
125239,
305464,
280888,
280891,
289087,
280897,
305480,
239944,
280906,
239947,
305485,
305489,
379218,
280919,
248153,
215387,
354653,
313700,
313705,
280937,
190832,
280946,
223606,
313720,
280956,
280959,
313731,
199051,
240011,
289166,
240017,
297363,
190868,
240021,
297365,
297368,
297372,
141725,
297377,
289186,
297391,
289201,
240052,
289207,
289210,
305594,
281024,
289218,
289221,
289227,
436684,
281045,
281047,
166378,
305647,
281075,
174580,
240124,
281084,
305662,
305664,
240129,
305666,
305668,
223749,
330244,
240132,
223752,
150025,
338440,
281095,
223757,
281102,
223763,
223765,
281113,
322074,
281116,
281121,
182819,
281127,
150066,
158262,
158266,
289342,
281154,
322115,
158283,
281163,
281179,
338528,
338532,
281190,
199273,
281196,
19053,
158317,
313973,
297594,
281210,
158347,
264845,
182926,
133776,
182929,
314003,
117398,
314007,
289436,
174754,
330404,
289448,
174764,
314029,
314033,
240309,
133817,
314045,
314047,
314051,
199364,
297671,
158409,
256716,
289493,
363234,
289513,
289522,
289525,
289532,
322303,
289537,
322310,
264969,
322314,
322318,
281372,
322341,
215850,
281388,
289593,
281401,
289601,
281410,
281413,
281414,
240458,
281420,
240468,
281430,
322393,
297818,
281435,
281438,
281442,
174955,
224110,
207733,
207737,
158596,
183172,
338823,
322440,
314249,
240519,
183184,
289687,
224151,
240535,
297883,
289694,
289696,
289700,
289712,
281529,
289724,
52163,
420829,
281567,
289762,
322534,
297961,
183277,
322550,
134142,
322563,
314372,
330764,
175134,
322599,
322610,
314421,
281654,
314427,
314433,
207937,
314441,
207949,
322642,
314456,
281691,
314461,
281702,
281704,
314474,
281708,
281711,
248995,
306341,
306344,
306347,
322734,
306354,
142531,
199877,
289991,
306377,
289997,
249045,
363742,
363745,
298216,
330988,
126190,
216303,
322801,
388350,
257302,
363802,
199976,
199978,
314671,
298292,
298294,
257334,
216376,
380226,
298306,
224584,
224587,
224594,
216404,
306517,
150870,
314714,
224603,
314718,
265568,
314723,
281960,
150890,
306539,
314732,
314736,
290161,
216436,
306549,
298358,
314743,
306552,
290171,
314747,
298365,
290174,
306555,
224641,
281987,
298372,
314756,
281990,
224647,
265604,
298377,
314763,
142733,
298381,
314768,
224657,
306581,
314773,
314779,
314785,
314793,
282025,
282027,
241068,
241070,
241072,
282034,
241077,
150966,
298424,
306618,
282044,
323015,
306635,
306640,
290263,
290270,
290275,
339431,
282089,
191985,
282098,
290291,
282101,
241142,
191992,
290298,
151036,
290302,
282111,
290305,
175621,
306694,
192008,
323084,
257550,
290321,
282130,
323090,
290325,
282133,
241175,
290328,
282137,
290332,
241181,
282142,
282144,
290344,
306731,
290349,
290351,
290356,
224849,
282195,
282199,
282201,
306778,
159324,
159330,
314979,
298598,
323176,
224875,
241260,
323181,
257658,
315016,
282249,
290445,
282255,
282261,
175770,
298651,
282269,
323229,
298655,
323231,
61092,
282277,
306856,
282295,
323260,
282300,
323266,
282310,
323273,
282319,
306897,
241362,
306904,
282328,
298714,
52959,
216801,
282337,
241380,
216806,
323304,
282345,
12011,
282356,
323318,
282364,
282367,
306945,
241412,
323333,
282376,
216842,
323345,
282388,
323349,
282392,
184090,
315167,
315169,
282402,
315174,
323367,
241448,
315176,
241450,
282410,
306988,
306991,
315184,
323376,
315190,
241464,
159545,
282425,
298811,
118593,
307009,
413506,
307012,
241475,
298822,
315211,
282446,
307027,
315221,
323414,
315223,
241496,
241498,
307035,
307040,
110433,
241509,
110438,
298860,
110445,
282478,
315249,
282481,
110450,
315251,
315253,
315255,
339838,
315267,
282499,
315269,
241544,
282505,
241546,
241548,
298896,
298898,
282514,
241556,
44948,
298901,
241560,
282520,
241563,
241565,
241567,
241569,
282531,
241574,
282537,
298922,
36779,
241581,
282542,
241583,
323504,
241586,
282547,
241588,
290739,
241590,
241592,
241598,
290751,
241600,
241605,
151495,
241610,
298975,
241632,
298984,
241640,
241643,
298988,
241646,
241649,
241652,
323574,
290807,
299003,
241661,
299006,
282623,
315396,
241669,
315397,
282632,
307211,
282639,
290835,
282645,
241693,
282654,
102438,
217127,
282669,
323630,
282681,
290877,
282687,
159811,
315463,
315466,
192589,
192596,
176213,
307287,
307290,
217179,
315482,
192605,
315483,
233567,
299105,
200801,
217188,
299109,
307303,
315495,
356457,
45163,
307307,
315502,
192624,
307314,
323700,
299126,
233591,
299136,
307329,
315524,
307338,
233613,
241813,
307352,
299164,
241821,
299167,
315552,
315557,
184486,
307370,
307372,
184492,
307374,
307376,
299185,
323763,
184503,
176311,
307385,
307386,
258235,
307388,
176316,
307390,
299200,
184512,
307394,
299204,
307396,
184518,
307399,
323784,
233679,
307409,
307411,
176343,
299225,
233701,
307432,
184572,
184579,
282893,
323854,
291089,
282906,
291104,
233766,
176435,
307508,
315701,
332086,
307510,
307512,
168245,
307515,
307518,
282942,
323917,
110926,
282957,
233808,
323921,
315733,
323926,
233815,
315739,
323932,
299357,
242018,
242024,
299373,
315757,
250231,
242043,
315771,
299388,
299391,
291202,
299398,
242057,
291212,
299405,
291222,
315801,
291226,
242075,
283033,
61855,
291231,
283042,
291238,
291241,
127403,
127405,
291247,
299440,
127407,
299444,
127413,
291254,
283062,
127417,
291260,
127421,
127424,
299457,
127429,
127434,
315856,
315860,
176597,
283095,
127447,
299481,
176605,
242143,
291299,
340454,
127463,
242152,
291305,
127466,
176620,
127474,
291314,
291317,
127480,
135672,
291323,
233979,
127485,
291330,
127490,
283142,
127497,
233994,
135689,
127500,
291341,
233998,
127506,
234003,
127509,
234006,
127511,
152087,
242202,
234010,
135707,
135710,
242206,
242208,
291361,
242220,
291378,
152118,
234038,
234041,
315961,
70213,
242250,
111193,
242275,
299620,
242279,
168562,
184952,
135805,
135808,
291456,
373383,
299655,
135820,
316051,
225941,
316054,
299672,
135834,
373404,
299677,
225948,
135839,
299680,
225954,
299684,
135844,
242343,
242345,
373421,
135870,
135873,
135876,
135879,
299720,
299723,
299726,
225998,
226002,
119509,
226005,
226008,
299740,
242396,
201444,
299750,
283368,
234219,
283372,
185074,
226037,
283382,
316151,
234231,
234236,
226045,
242431,
209665,
299778,
234242,
242436,
234246,
226056,
291593,
234248,
242443,
234252,
242445,
234254,
291601,
234258,
242450,
242452,
234261,
201496,
234264,
234266,
234269,
234272,
234274,
152355,
299814,
234278,
283432,
234281,
234284,
234287,
283440,
185138,
242483,
234292,
234296,
234298,
160572,
283452,
234302,
234307,
242499,
234309,
316233,
234313,
316235,
234316,
283468,
234319,
242511,
234321,
234324,
185173,
201557,
234329,
234333,
308063,
234336,
242530,
349027,
234338,
234341,
234344,
234347,
177004,
234350,
324464,
234353,
152435,
177011,
234356,
234358,
234362,
234364,
291711,
234368,
291714,
234370,
291716,
234373,
201603,
234375,
226182,
308105,
226185,
234379,
234384,
234388,
234390,
226200,
234393,
209818,
308123,
234396,
324504,
234398,
291742,
324508,
234401,
291748,
234405,
291750,
324518,
324520,
234407,
324522,
234410,
291756,
291754,
226220,
324527,
291760,
234417,
201650,
324531,
234414,
234422,
226230,
324536,
275384,
234428,
291773,
242623,
324544,
234431,
234434,
324546,
324548,
226239,
234437,
226245,
234439,
234443,
291788,
193486,
234446,
193488,
234449,
275406,
234452,
234455,
234459,
234461,
234464,
234467,
234470,
168935,
5096,
324585,
234475,
234478,
316400,
234481,
316403,
234484,
234485,
234487,
234490,
234493,
316416,
234496,
234501,
308231,
234504,
234507,
234510,
234515,
300054,
316439,
234520,
234519,
234523,
234526,
234528,
300066,
234532,
300069,
234535,
234537,
234540,
234543,
234546,
275508,
300085,
234549,
300088,
234553,
234558,
316479,
234561,
316483,
160835,
234563,
308291,
234568,
234570,
316491,
234572,
300108,
234574,
300115,
234580,
234581,
242777,
234585,
275545,
234590,
234593,
234595,
234597,
300133,
234601,
300139,
234605,
160879,
234607,
275569,
234610,
316530,
300148,
234614,
144506,
234618,
234620,
275579,
234623,
226433,
234627,
275588,
234629,
242822,
234634,
234636,
177293,
234640,
275602,
234643,
308373,
324757,
234647,
226453,
275608,
234650,
308379,
234648,
300189,
324766,
119967,
234653,
234657,
324768,
283805,
242852,
300197,
234661,
177318,
234664,
275626,
234667,
316596,
308414,
234687,
300223,
300226,
308418,
234692,
300229,
308420,
308422,
283844,
300234,
283850,
300238,
300241,
316625,
300243,
300245,
316630,
300248,
300253,
300256,
300258,
300260,
234726,
300263,
300265,
300267,
161003,
300270,
300272,
120053,
300278,
275703,
316663,
300284,
275710,
300287,
292097,
300289,
161027,
300292,
300294,
275719,
234760,
177419,
300299,
242957,
300301,
349451,
177424,
275725,
283917,
349464,
415009,
283939,
259367,
292143,
283951,
300344,
226617,
243003,
283963,
226628,
300357,
283973,
177482,
283983,
316758,
357722,
316766,
316768,
292192,
218464,
292197,
316774,
243046,
218473,
284010,
136562,
324978,
333178,
275834,
275836,
275840,
316803,
316806,
226696,
316811,
226699,
316814,
226703,
300433,
234899,
300436,
357783,
316824,
316826,
300448,
144807,
144810,
144812,
144814,
227426,
144820,
374196,
284084,
292279,
284087,
144826,
144828,
144830,
144832,
227430,
144835,
144837,
38342,
144839,
144841,
144844,
144847,
144852,
144855,
103899,
300507,
333280,
218597,
292329,
300523,
259565,
300527,
308720,
259567,
292338,
316917,
292343,
308727,
300537,
316933,
316947,
308757,
308762,
316959,
284194,
284196,
235045,
284199,
284204,
284206,
284209,
284211,
194101,
284213,
316983,
194103,
284215,
308790,
284218,
226877,
284223,
284226,
284228,
243268,
292421,
284231,
226886,
284234,
366155,
317004,
276043,
284238,
226895,
284241,
194130,
284243,
300628,
284245,
276053,
284247,
317015,
235097,
243290,
284249,
284253,
300638,
243293,
284255,
284258,
292452,
292454,
284263,
177766,
292458,
284267,
292461,
284272,
284274,
284278,
292470,
276086,
292473,
284283,
276093,
284286,
276095,
284288,
292479,
284290,
325250,
284292,
292485,
292481,
276098,
284297,
317066,
284299,
317068,
284301,
276109,
284303,
284306,
276114,
284308,
284312,
284314,
284316,
276127,
284320,
284322,
284327,
284329,
317098,
284331,
276137,
284333,
284335,
284337,
284339,
300726,
284343,
284346,
284350,
358080,
276160,
284354,
358083,
284358,
358089,
284362,
276170,
284365,
276175,
284368,
276177,
284370,
358098,
284372,
317138,
284377,
284379,
284384,
358114,
284386,
358116,
276197,
317158,
358119,
284392,
325353,
358122,
284394,
284397,
358126,
276206,
358128,
284399,
358133,
358135,
276216,
358138,
300795,
358140,
284413,
358142,
358146,
317187,
284418,
317189,
317191,
284428,
300816,
300819,
317207,
284440,
300828,
300830,
276255,
300832,
325408,
300834,
317221,
227109,
358183,
186151,
276268,
300845,
243504,
300850,
284469,
276280,
325436,
358206,
276291,
366406,
276295,
300872,
292681,
153417,
358224,
284499,
276308,
284502,
317271,
178006,
276315,
292700,
317279,
284511,
227175,
292715,
300912,
292721,
284529,
300915,
284533,
292729,
317306,
284540,
292734,
325512,
169868,
276365,
317332,
358292,
399252,
284564,
284566,
350106,
284572,
276386,
284579,
276388,
358312,
317353,
292776,
276395,
284585,
292784,
276402,
358326,
161718,
358330,
276411,
276425,
301009,
301011,
301013,
292823,
358360,
301017,
301015,
292828,
276446,
153568,
276452,
292839,
276455,
350186,
292843,
276460,
178161,
227314,
325624,
350200,
276472,
317435,
276479,
350210,
276482,
178181,
317446,
276485,
350218,
276490,
292876,
350222,
317456,
276496,
317458,
178195,
243733,
243740,
317468,
317472,
325666,
243751,
292904,
178224,
276528,
243762,
309298,
325685,
325689,
235579,
325692,
235581,
178238,
276539,
243779,
325700,
284739,
292934,
243785,
276553,
350293,
350295,
309337,
227418,
350299,
350302,
194654,
350304,
178273,
309346,
227423,
194660,
350308,
309350,
309348,
292968,
309352,
350313,
309354,
350316,
276583,
301163,
301167,
276586,
350321,
227440,
284786,
276595,
350325,
252022,
350328,
292985,
301178,
292989,
301185,
292993,
350339,
317570,
317573,
350342,
350345,
350349,
301199,
317584,
325777,
350354,
350357,
350359,
350362,
350366,
276638,
153765,
284837,
350375,
350379,
350381,
350383,
350385,
350387,
350389,
350395,
350397,
350399,
227520,
350402,
227522,
301252,
350406,
227529,
301258,
309450,
276685,
309455,
276689,
309462,
301272,
276699,
194780,
309468,
309471,
301283,
317672,
317674,
325867,
243948,
194801,
309491,
309494,
243960,
227583,
276735,
276739,
211204,
276742,
227596,
325910,
309530,
342298,
211232,
317729,
276775,
211241,
325937,
325943,
211260,
260421,
285002,
276811,
235853,
276816,
235858,
276829,
276833,
391523,
276836,
293227,
276843,
293232,
276848,
186744,
211324,
227709,
285061,
366983,
317833,
178572,
285070,
285077,
178583,
227738,
317853,
276896,
317858,
342434,
285093,
317864,
285098,
276907,
235955,
276917,
293304,
293307,
293314,
309707,
293325,
129486,
317910,
293336,
235996,
317917,
293343,
358880,
276961,
293346,
276964,
293352,
236013,
293364,
301562,
293370,
317951,
309764,
301575,
121352,
293387,
236043,
342541,
317963,
113167,
55822,
309779,
317971,
309781,
55837,
227879,
293417,
227882,
309804,
293421,
105007,
236082,
285236,
23094,
277054,
244288,
219714,
129603,
301636,
318020,
301639,
301643,
285265,
309844,
277080,
309849,
285277,
285282,
326244,
318055,
277100,
309871,
121458,
277106,
170618,
170619,
309885,
309888,
277122,
227975,
277128,
285320,
301706,
318092,
326285,
334476,
318094,
277136,
277139,
227992,
318108,
285340,
318110,
227998,
137889,
383658,
285357,
318128,
277170,
293555,
342707,
318132,
154292,
277173,
285368,
277177,
277181,
318144,
277187,
277191,
277194,
277196,
277201,
342745,
137946,
342747,
342749,
113378,
203491,
228069,
277223,
342760,
56041,
285417,
56043,
56045,
277232,
228081,
56059,
310015,
310020,
310029,
228113,
285459,
277273,
293659,
326430,
228128,
285474,
293666,
228135,
318248,
277291,
318253,
293677,
285489,
301876,
293685,
285494,
301880,
285499,
301884,
293696,
310080,
277317,
293706,
277329,
162643,
310100,
301911,
277337,
301921,
400236,
236397,
162671,
326514,
310134,
236408,
15224,
277368,
416639,
416640,
113538,
310147,
416648,
277385,
187274,
39817,
301972,
424853,
277405,
277411,
310179,
293798,
293802,
236460,
277426,
293811,
276579,
293817,
293820,
203715,
326603,
342994,
293849,
293861,
228327,
228328,
318442,
228332,
326638,
277486,
351217,
318450,
293876,
293877,
285686,
302073,
121850,
293882,
302075,
285690,
293887,
277504,
277507,
277511,
293899,
277519,
293908,
293917,
293939,
318516,
277561,
277564,
310336,
7232,
293956,
277573,
228422,
293960,
310344,
277577,
277583,
203857,
293971,
310355,
310359,
236632,
277594,
138332,
277598,
203872,
285792,
277601,
310374,
203879,
310376,
228460,
318573,
203886,
187509,
285815,
367737,
285817,
302205,
285821,
392326,
294026,
285835,
302218,
162964,
384148,
187542,
302231,
285849,
302233,
285852,
302237,
285854,
285856,
302241,
285862,
277671,
302248,
64682,
277678,
294063,
294065,
302258,
277687,
294072,
318651,
277695,
318657,
244930,
302275,
130244,
302277,
228550,
302282,
310476,
302285,
302288,
310481,
302290,
203987,
302292,
302294,
310486,
302296,
384222,
310498,
285927,
318698,
302315,
228592,
294132,
138485,
204026,
228606,
204031,
64768,
310531,
138505,
228617,
318742,
204067,
277798,
130345,
277801,
277804,
285997,
384302,
285999,
277807,
113969,
277811,
318773,
318776,
277816,
286010,
277819,
294204,
417086,
277822,
302403,
294211,
384328,
277832,
277836,
294221,
146765,
294223,
326991,
277839,
277842,
277847,
277850,
179547,
277853,
277857,
302436,
277860,
294246,
327015,
310632,
327017,
351594,
277864,
277869,
277872,
351607,
310648,
277880,
310651,
277884,
277888,
310657,
351619,
294276,
310659,
327046,
277892,
253320,
310665,
318858,
277894,
277898,
277903,
310672,
351633,
277905,
277908,
277917,
310689,
277921,
130468,
277928,
277932,
310703,
277937,
310710,
130486,
310712,
277944,
310715,
277947,
302526,
277950,
277953,
302534,
310727,
245191,
64966,
277959,
277963,
302541,
277966,
302543,
310737,
277971,
228825,
277978,
310749,
277981,
277984,
310755,
277989,
277991,
187880,
277995,
310764,
286188,
278000,
228851,
310772,
278003,
278006,
40440,
212472,
278009,
40443,
310780,
286203,
40448,
228864,
286214,
302603,
302614,
302617,
286233,
302621,
286240,
187936,
146977,
187939,
40484,
294435,
40486,
286246,
294440,
40488,
294439,
294443,
40491,
294445,
245288,
310831,
286248,
40499,
40502,
212538,
40507,
40511,
40513,
228933,
40521,
286283,
40525,
40527,
212560,
400976,
228944,
40533,
40537,
40539,
40541,
278109,
40544,
40548,
40550,
40552,
286312,
40554,
286313,
310892,
40557,
40560,
188022,
122488,
294521,
343679,
294537,
310925,
286354,
278163,
302740,
122517,
278168,
179870,
327333,
229030,
212648,
302764,
278188,
319153,
278196,
319163,
302781,
319171,
302789,
294599,
278216,
294601,
302793,
343757,
212690,
319187,
286420,
229076,
286425,
319194,
278235,
278238,
229086,
286432,
294625,
294634,
302838,
319226,
286460,
278274,
302852,
278277,
302854,
294664,
311048,
352008,
319243,
311053,
302862,
319251,
294682,
278306,
188199,
294701,
319280,
278320,
319290,
229192,
302925,
188247,
188252,
237409,
294776,
360317,
294785,
327554,
360322,
40840,
40851,
294803,
188312,
294811,
237470,
319390,
40865,
319394,
294817,
294821,
311209,
180142,
343983,
188340,
40886,
319419,
294844,
294847,
393177,
294876,
294879,
294883,
393190,
294890,
311279,
278513,
237555,
278516,
311283,
278519,
237562
] |
338c2ba9031337272b40894a1b6a9bd8ab43e1c3 | 6fafb34b7ff6d23ec8b45f2d94dd18a27e52a202 | /AliEng/ResultViewController.swift | 42c130dd206bd09baddc53a8c75c969188b88a34 | [] | no_license | turlygazhy/alieng-ios | 7a83a76714f344570f3d9e944d4dd90a9960bac0 | b5a539b441265d7650f44c10b51db98ea17a3d28 | refs/heads/main | 2023-05-11T10:41:53.377844 | 2021-05-30T09:17:49 | 2021-05-30T09:17:49 | 371,240,266 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,869 | swift | //
// ResultViewController.swift
// AliEng
//
// Created by Umid on 29/05/21.
//
import UIKit
class ResultViewController: UIViewController, MDRotatingPieChartDelegate, MDRotatingPieChartDataSource{
@IBOutlet weak var containerView: UIView!
var slicesData = [Data]()
var pieChart:MDRotatingPieChart!
override func viewDidLoad() {
super.viewDidLoad()
pieChart = MDRotatingPieChart(frame: CGRect(x: 00, y: 0, width: containerView.frame.width, height: containerView.frame.height - 20))
pieChart.delegate = self
pieChart.datasource = self
containerView.addSubview(pieChart)
/*
Here you can dig into some properties
-------------------------------------
*/
var properties = Properties()
properties.smallRadius = 50
properties.bigRadius = 120
properties.expand = 25
properties.displayValueTypeInSlices = .percent
properties.displayValueTypeCenter = .label
properties.fontTextInSlices = UIFont(name: "Arial", size: 12)!
properties.fontTextCenter = UIFont(name: "Arial", size: 10)!
properties.enableAnimation = true
properties.animationDuration = 0.5
let nf = NumberFormatter()
nf.groupingSize = 3
nf.maximumSignificantDigits = 2
nf.minimumSignificantDigits = 2
properties.nf = nf
pieChart.properties = properties
}
@IBAction func okAction(_ sender: UIButton) {
self.navigationController?.popToRootViewController(animated: true)
}
func didOpenSliceAtIndex(_ index: Int) {
print("Open slice at \(index)")
}
func didCloseSliceAtIndex(_ index: Int) {
print("Close slice at \(index)")
}
func willOpenSliceAtIndex(_ index: Int) {
print("Will open slice at \(index)")
}
func willCloseSliceAtIndex(_ index: Int) {
print("Will close slice at \(index)")
}
//Datasource
func colorForSliceAtIndex(_ index:Int) -> UIColor {
return slicesData[index].color
}
func valueForSliceAtIndex(_ index:Int) -> CGFloat {
return slicesData[index].value
}
func labelForSliceAtIndex(_ index:Int) -> String {
return "" //slicesData[index].label
}
func numberOfSlices() -> Int {
return slicesData.count
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
@objc func refresh() {
pieChart.build()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
-1
] |
ce3808ae4866988042df574182030866870f4a74 | 726de5a069c2e4bb03102b948f4d6ad54364ab9a | /Source/Scene/Search/SearchViewModel.swift | dce4577d0f6f4c4263aefa664d5de7fc9a994add | [
"MIT"
] | permissive | kcharliek/MyAppStore | d8a2edeef864067e6ca04d77d2284ee3b118b0e1 | a5f9421208cf6b8a916829117abcd59ad011b2c4 | refs/heads/main | 2023-03-25T13:29:33.450693 | 2021-03-25T14:21:03 | 2021-03-25T14:21:03 | 351,456,751 | 13 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,794 | swift | //
// SearchViewModel.swift
// MyAppStore
//
// Created by CHANHEE KIM on 2021/03/21.
//
import Foundation
class SearchViewModel {
// MARK: - Variables
lazy var searchHistoryViewModel: SearchHistoryViewModel = {
SearchHistoryViewModel(searchHistoryProvider: searchHistoryProvider)
}()
let searchResultsContainerViewModel: SearchResultsContainerViewModel
private let searchResultsContainerViewFactory: SearchResultsContainerViewFactory
private let searchHistoryRecorder: SearchHistoryRecorder
private let searchHistoryProvider: SearchHistoryProvider
// MARK: - Initializer
init(searchResultsContainerViewFactory: SearchResultsContainerViewFactory, searchHistoryRecorder: SearchHistoryRecorder, searchHistoryProvider: SearchHistoryProvider) {
self.searchResultsContainerViewFactory = searchResultsContainerViewFactory
self.searchHistoryRecorder = searchHistoryRecorder
self.searchHistoryProvider = searchHistoryProvider
self.searchResultsContainerViewModel = searchResultsContainerViewFactory.makeSearchResultsContainerViewModel()
bind()
}
private func bind() {
searchHistoryRecorder.onSearchHistoryUpdated = { [weak self] in
self?.searchHistoryViewModel.updateSearchHistory()
}
}
// MARK: - Methods
func makeSearchResultsContainerViewController() -> SearchResultsContainerViewController {
return searchResultsContainerViewFactory.makeSearchResultsContainerViewController(viewModel: searchResultsContainerViewModel)
}
func updateSearchHistory() {
searchHistoryViewModel.updateSearchHistory()
}
func searchApp(with query: String) {
searchResultsContainerViewModel.search(with: query, target: .app)
}
}
| [
-1
] |
0bbbb08770ae67306de4d9ff8716c8ca74f58b1a | 5106d5f10573823e35f674765ed7126358ba59f4 | /12-SwiftUI/SwiftUIExampleLesson/SwiftUIExample/ExampleView.swift | 38f5d49be2cc9d720535ae6cd737b307735fbc06 | [] | no_license | AckeeEDU/bi-ios-2019 | e1923058c22399160354e16a419905c37229dd0b | ff4aebd0d610717e0156be881ddcc5e86cc0a002 | refs/heads/master | 2020-07-04T16:56:24.031114 | 2020-02-03T21:22:32 | 2020-02-03T21:22:32 | 202,347,234 | 4 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 916 | swift | //
// ExampleView.swift
// SwiftUIExample
//
// Created by Jakub Olejník on 18/12/2019.
// Copyright © 2019 CVUT. All rights reserved.
//
import SwiftUI
struct ExampleView: View {
@State var textFieldValue = ""
@State var isSheetVisible = false
var body: some View {
VStack(spacing: 10) {
TextField("Enter value", text: $textFieldValue)
Button(action: buttonTapped) {
Text("Submit")
}
}
.actionSheet(isPresented: $isSheetVisible) {
ActionSheet(title: Text("Title"), message: Text("message"), buttons: [
.destructive(Text("Destructive")),
.cancel()
])
}
}
private func buttonTapped() {
isSheetVisible = true
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
}
}
| [
-1
] |
4dc21c00544c9697d3b2659fbe58c506bc094970 | c517b10d20dbee9bd832bdae074674af980e9922 | /Gittest/AppDelegate.swift | 0b7bcac42b9cd1be67f9b7b9faa67d8b52f98721 | [] | no_license | Nevada-Apple-Tree/AppleTree | 5f5607a02ab0ece9d6fe18154d26c1d81cf0adb1 | 59ddc73af2088703caaea9a81553063244afbc04 | refs/heads/main | 2023-07-06T12:25:24.309028 | 2021-08-14T18:37:11 | 2021-08-14T18:37:11 | 348,564,540 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,347 | swift | //
// AppDelegate.swift
// Gittest
//
// Created by Jonzo Jimenez on 8/14/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| [
393222,
393224,
393230,
393250,
344102,
393261,
393266,
213048,
385081,
376889,
393275,
376905,
327756,
254030,
368727,
180313,
368735,
180320,
376931,
368752,
417924,
262283,
377012,
327871,
180416,
377036,
180431,
377046,
418007,
418010,
377060,
327914,
205036,
393456,
393460,
418043,
336123,
385280,
336128,
262404,
180490,
164106,
368911,
262416,
262422,
377117,
262436,
336180,
262454,
393538,
262472,
344403,
213332,
65880,
262496,
418144,
262499,
213352,
246123,
262507,
262510,
213372,
385419,
393612,
262550,
262552,
385440,
385443,
262566,
385451,
262573,
393647,
385458,
262586,
344511,
262592,
360916,
369118,
328177,
328179,
328182,
328189,
328192,
164361,
410128,
393747,
254490,
188958,
385570,
33316,
197159,
377383,
352821,
197177,
418363,
188987,
369223,
385609,
385616,
352864,
369253,
262760,
352874,
352887,
254587,
377472,
148105,
377484,
352918,
98968,
344744,
361129,
336555,
385713,
434867,
164534,
336567,
328378,
164538,
328386,
352968,
344776,
418507,
352971,
352973,
385742,
385748,
361179,
189153,
369381,
361195,
418553,
344831,
336643,
344835,
344841,
361230,
336659,
418580,
418585,
434970,
369435,
418589,
262942,
418593,
336675,
328484,
418598,
418605,
336696,
361273,
328515,
336708,
328519,
361288,
336711,
328522,
336714,
426841,
254812,
361309,
197468,
361315,
361322,
328573,
377729,
369542,
361360,
222128,
345035,
345043,
386003,
386011,
386018,
386022,
435187,
328714,
361489,
386069,
336921,
386073,
336925,
345118,
377887,
345133,
345138,
386101,
361536,
197707,
345169,
156761,
361567,
148578,
345199,
386167,
361593,
410745,
361598,
214149,
345222,
386186,
337047,
345246,
214175,
337071,
337075,
345267,
386258,
328924,
66782,
222437,
328941,
386285,
386291,
345376,
353570,
345379,
410917,
345382,
337205,
345399,
378169,
369978,
337222,
337229,
337234,
263508,
402791,
345448,
271730,
378227,
271745,
181638,
353673,
181643,
181654,
230809,
181673,
181681,
337329,
181684,
361917,
181696,
337349,
337365,
271839,
329191,
361960,
329194,
116210,
337398,
337415,
329226,
419339,
419343,
419349,
419355,
370205,
419359,
394786,
419362,
370213,
419368,
419376,
206395,
214593,
419400,
419402,
353867,
419406,
419410,
345701,
394853,
222830,
370297,
403070,
353919,
403075,
198280,
345736,
403091,
345749,
419483,
345757,
345762,
419491,
345765,
419497,
419501,
370350,
419506,
419509,
419512,
337592,
419517,
337599,
419527,
419530,
419535,
272081,
419542,
394966,
419544,
181977,
345818,
419547,
419550,
419559,
337642,
419563,
337645,
370415,
337659,
141051,
337668,
362247,
395021,
362255,
116509,
345887,
378663,
345905,
354106,
354111,
247617,
354117,
370503,
329544,
345930,
370509,
354130,
247637,
337750,
370519,
313180,
354142,
354150,
354156,
345964,
345967,
345970,
345974,
403320,
354172,
247691,
337808,
247700,
329623,
436126,
436132,
337833,
362413,
337844,
346057,
247759,
346063,
329697,
354277,
190439,
247789,
354313,
346139,
436289,
378954,
395339,
338004,
100453,
329832,
329855,
329867,
329885,
411805,
346272,
362660,
100524,
387249,
379066,
387260,
256191,
395466,
346316,
411861,
411864,
411868,
411873,
379107,
411876,
387301,
346343,
338152,
387306,
387312,
346355,
436473,
379134,
411903,
411916,
379152,
395538,
387349,
338199,
387352,
182558,
395566,
248111,
362822,
436555,
190796,
379233,
354673,
248186,
420236,
379278,
272786,
354727,
338352,
330189,
338381,
338386,
256472,
338403,
338409,
248308,
199164,
330252,
199186,
420376,
330267,
354855,
10828,
199249,
174695,
248425,
191084,
338543,
191092,
346742,
330383,
354974,
150183,
174774,
248504,
174777,
223934,
355024,
273108,
355028,
264918,
183005,
256734,
436962,
338660,
338664,
264941,
363251,
207619,
264964,
338700,
256786,
199452,
363293,
396066,
346916,
396069,
215853,
355122,
355131,
355140,
355143,
338763,
355150,
330580,
355166,
265055,
265058,
355175,
387944,
355179,
330610,
330642,
355218,
412599,
207808,
379848,
396245,
248792,
248798,
347105,
257008,
183282,
265207,
330748,
265214,
330760,
330768,
248862,
396328,
347176,
158761,
199728,
330800,
396336,
396339,
339001,
388154,
388161,
347205,
248904,
330826,
248914,
412764,
339036,
257120,
265320,
248951,
420984,
330889,
347287,
248985,
339097,
44197,
380070,
339112,
249014,
126144,
330958,
330965,
265432,
265436,
388319,
388347,
175375,
159005,
175396,
208166,
273708,
347437,
372015,
347441,
372018,
199988,
44342,
175415,
396600,
437566,
175423,
437570,
437575,
437583,
331088,
437587,
331093,
396633,
175450,
437595,
175457,
208227,
175460,
175463,
265580,
437620,
175477,
249208,
175483,
175486,
249214,
175489,
249218,
249227,
175513,
175516,
396705,
175522,
355748,
380332,
396722,
208311,
388542,
372163,
216517,
380360,
216522,
339404,
372176,
208337,
339412,
413141,
339417,
249308,
339420,
339424,
339428,
339434,
249328,
69113,
372228,
208398,
380432,
175635,
265778,
265795,
396872,
265805,
224853,
224857,
257633,
224870,
372327,
257646,
372337,
224884,
224887,
224890,
224894,
224897,
372353,
216707,
126596,
421508,
224904,
224909,
11918,
159374,
224913,
126610,
339601,
224916,
224919,
126616,
224922,
208538,
224926,
224929,
224932,
224936,
257704,
224942,
257712,
224947,
257716,
257720,
224953,
257724,
224959,
257732,
224965,
224969,
339662,
224975,
257747,
224981,
224986,
257761,
224993,
257764,
224999,
339695,
225012,
257787,
225020,
339710,
257790,
225025,
257794,
257801,
339721,
257804,
225038,
257807,
225043,
372499,
167700,
225048,
257819,
225053,
225058,
257833,
225066,
257836,
413484,
225070,
225073,
372532,
257845,
225079,
397112,
225082,
397115,
225087,
225092,
225096,
323402,
257868,
257871,
225103,
397139,
225108,
225112,
257883,
257886,
225119,
257890,
339814,
225127,
274280,
257896,
257901,
225137,
339826,
257908,
225141,
257912,
257916,
225148,
257920,
225155,
339844,
225165,
397200,
225170,
380822,
225175,
225180,
118691,
184244,
372664,
372702,
372706,
356335,
380918,
405533,
430129,
266294,
266297,
421960,
356439,
421990,
266350,
356466,
266362,
381068,
225423,
250002,
250004,
225429,
356506,
225437,
135327,
225441,
438433,
225444,
438436,
225447,
438440,
225450,
258222,
225455,
225458,
225461,
225466,
389307,
225470,
381120,
372929,
430274,
225475,
389320,
225484,
225487,
225490,
225493,
266453,
225496,
225499,
225502,
225505,
356578,
225510,
217318,
225514,
225518,
372976,
381176,
389380,
61722,
356637,
356640,
356643,
356646,
266536,
356649,
356655,
332080,
340275,
356660,
397622,
332090,
225597,
332097,
201028,
348488,
332106,
332117,
348502,
250199,
250202,
332125,
250210,
332152,
389502,
250238,
332161,
356740,
332172,
373145,
340379,
389550,
324030,
266687,
160234,
127471,
340472,
381436,
324094,
266754,
324099,
324102,
324111,
340500,
324117,
324131,
332324,
381481,
324139,
356907,
324142,
356916,
324149,
324155,
348733,
324164,
348743,
381512,
324170,
324173,
324176,
389723,
332380,
381545,
340627,
373398,
184982,
258721,
332453,
332459,
389805,
332463,
381617,
332471,
332483,
332486,
373449,
332493,
357069,
357073,
332511,
332520,
340718,
332533,
348924,
389892,
373510,
389926,
152370,
348978,
340789,
348982,
398139,
127814,
357201,
357206,
389978,
430939,
357211,
357214,
201579,
201582,
349040,
340849,
430965,
381813,
324472,
398201,
340858,
324475,
430972,
340861,
324478,
119674,
324481,
373634,
398211,
324484,
324487,
381833,
324492,
324495,
324498,
430995,
324501,
324510,
422816,
324513,
398245,
201637,
324524,
340909,
324533,
324538,
324541,
398279,
340939,
340941,
209873,
340957,
431072,
398306,
340963,
209895,
201711,
349172,
381946,
349180,
439294,
431106,
209943,
250914,
357410,
185380,
357418,
209965,
209971,
209975,
209979,
209987,
209990,
341071,
349267,
250967,
210010,
341091,
210025,
210030,
210036,
210039,
349308,
210044,
349311,
160895,
152703,
210052,
349319,
210055,
218247,
210067,
210077,
210080,
251044,
210084,
185511,
210095,
210098,
210107,
210115,
332997,
210127,
333009,
210131,
333014,
210138,
210143,
218354,
218360,
251128,
275712,
275715,
275721,
349459,
333078,
251160,
349484,
349491,
251189,
415033,
251210,
357708,
210260,
365911,
259421,
365921,
333154,
333162,
234866,
390516,
333175,
357755,
251271,
374160,
112020,
349590,
357792,
259515,
415166,
415185,
366034,
366038,
415191,
415193,
415196,
415199,
423392,
333284,
415207,
366056,
366061,
415216,
210420,
415224,
423423,
415257,
415263,
366117,
415270,
144939,
415278,
415281,
415285,
210487,
415290,
415293,
349761,
415300,
333386,
366172,
333413,
423528,
423532,
210544,
415353,
333439,
415361,
267909,
153227,
333498,
210631,
333511,
259788,
358099,
153302,
333534,
366307,
366311,
431851,
366318,
210672,
366321,
366325,
210695,
268041,
210698,
366348,
210706,
399128,
333594,
210719,
358191,
366387,
210739,
399159,
358200,
325440,
366401,
341829,
325446,
46920,
341834,
341838,
341843,
415573,
341851,
350045,
399199,
259938,
399206,
268143,
358255,
399215,
358259,
341876,
333689,
243579,
325504,
333698,
333708,
333724,
382890,
350146,
358371,
350189,
350193,
350202,
333818,
350206,
350213,
268298,
350224,
350231,
333850,
350237,
350240,
350244,
350248,
178218,
350251,
350256,
350259,
350271,
243781,
350285,
374864,
342111,
342133,
374902,
432271,
333997,
334011,
260289,
260298,
350410,
350416,
350422,
211160,
350425,
268507,
334045,
350445,
375026,
358644,
350458,
350461,
350464,
325891,
350467,
350475,
375053,
268559,
350480,
432405,
350486,
325914,
350490,
325917,
350493,
325919,
350498,
194852,
350504,
358700,
350509,
391468,
358704,
358713,
358716,
383306,
334161,
383321,
383330,
383333,
391530,
383341,
334203,
268668,
194941,
391563,
366990,
416157,
342430,
268701,
375208,
326058,
375216,
334262,
334275,
326084,
358856,
195039,
334304,
334311,
375277,
334321,
350723,
391690,
186897,
342545,
334358,
342550,
342554,
334363,
358941,
350761,
252461,
334384,
383536,
358961,
334394,
252482,
219718,
334407,
334420,
350822,
375400,
334465,
334468,
162445,
326290,
342679,
342683,
260766,
342710,
244409,
260797,
260801,
350917,
154317,
391894,
154328,
416473,
64230,
113388,
342766,
375535,
203506,
342776,
391937,
391948,
375568,
326416,
375571,
375574,
162591,
326441,
383793,
326451,
326454,
326460,
375612,
260924,
244540,
326467,
244551,
326473,
326477,
326485,
416597,
326490,
342874,
326502,
375656,
433000,
326507,
326510,
211825,
211831,
351097,
392060,
359295,
351104,
342915,
400259,
236430,
342930,
252822,
392091,
400285,
252836,
359334,
211884,
400306,
351168,
359361,
326598,
359366,
359382,
359388,
383967,
343015,
359407,
261108,
244726,
261111,
383997,
261129,
359451,
261147,
211998,
261153,
261159,
359470,
359476,
343131,
384098,
384101,
384107,
367723,
187502,
343154,
384114,
212094,
351364,
384135,
384139,
384143,
351381,
384160,
384168,
367794,
384181,
367800,
384191,
351423,
384198,
326855,
244937,
253130,
343244,
146642,
359649,
343270,
351466,
351479,
384249,
343306,
261389,
359694,
384269,
253200,
261393,
384275,
245020,
245029,
171302,
351534,
376110,
245040,
384314,
425276,
384323,
212291,
343365,
212303,
367965,
343393,
343398,
367980,
425328,
343409,
253303,
154999,
343417,
327034,
245127,
384397,
245136,
245142,
245145,
343450,
245148,
245151,
245154,
245157,
245162,
327084,
359865,
384443,
146876,
327107,
384453,
327110,
327115,
327117,
359886,
359890,
343507,
368092,
343534,
343539,
368119,
343544,
368122,
409091,
359947,
359955,
359983,
343630,
155239,
327275,
245357,
138864,
155254,
155273,
368288,
245409,
425638,
425649,
155322,
425662,
155327,
155351,
155354,
212699,
155363,
245475,
155371,
245483,
409335,
155393,
155403,
155422,
360223,
155438,
155442,
155447,
417595,
155461,
360261,
376663,
155482,
261981,
425822,
155487,
376671,
155490,
155491,
327531,
261996,
376685,
261999,
262002,
327539,
425845,
262005,
147317,
262008,
262011,
155516,
155521,
155525,
360326,
376714,
155531,
262027,
262030,
262033,
262036,
262039,
262042,
155549,
262045,
262048,
262051,
327589,
155559,
155562,
155565,
393150,
384977,
393169,
155611,
155619,
253923,
155621,
253926,
327654,
204784,
393203,
360438,
253943,
393206,
393212,
155646
] |
4cecafc558977fee5414c084c6f73cec3ced0983 | 2e8b7b524aa74fb266d5a3eac319a87f07c7daf0 | /Bento/StyleSheets/BaseStackViewStyleSheet.swift | b0b378735812e261ad125653b31319cf47ab3bc1 | [
"MIT"
] | permissive | babylonhealth/Bento | d33f8f6d67450c6a057ba9714a6ddc074a1cdc63 | 635d6d25e9152ba38aba8620e307431a0b8db4dd | refs/heads/develop | 2023-09-01T16:57:55.476492 | 2019-06-20T17:13:14 | 2019-06-20T17:13:14 | 118,751,888 | 48 | 5 | MIT | 2021-04-29T13:33:30 | 2018-01-24T10:47:12 | Swift | UTF-8 | Swift | false | false | 1,189 | swift | import UIKit
open class BaseStackViewStyleSheet<View: BaseStackView>: StackViewStyleSheet<View> {
public var backgroundColor: UIColor?
public var borderColor: UIColor?
public var cornerRadius: CGFloat
public var borderWidth: CGFloat
public init(
axis: NSLayoutConstraint.Axis,
spacing: CGFloat,
distribution: UIStackView.Distribution,
alignment: UIStackView.Alignment,
backgroundColor: UIColor? = nil,
borderColor: UIColor? = nil,
cornerRadius: CGFloat = 0.0,
borderWidth: CGFloat = 0.0
) {
self.backgroundColor = backgroundColor
self.borderColor = borderColor
self.cornerRadius = cornerRadius
self.borderWidth = borderWidth
super.init(
axis: axis,
spacing: spacing,
distribution: distribution,
alignment: alignment
)
}
open func apply(to element: BaseStackView) {
super.apply(to: element)
element.backgroundColor = backgroundColor
element.cornerRadius = cornerRadius
element.borderColor = borderColor?.cgColor
element.borderWidth = borderWidth
}
}
| [
-1
] |
808c7ee05a592e62216b7be20c172036125659d8 | 98200da8f578b54d71ec58704ecaf235876d8bd0 | /Sources/OfficeFileReader/MS-DOC/StkCharUpxGrLPUpxRM.swift | 09d70724c298935680b4a8826c25de94133c10e5 | [] | no_license | hughbe/OfficeFileReader | 7ff9f37b7db2324e36d0184edad62152278dfee2 | a26192f6f6ff1a925abddd446830794ded646c48 | refs/heads/master | 2022-07-30T01:29:12.973738 | 2020-12-16T15:01:25 | 2020-12-16T15:01:25 | 315,408,906 | 7 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,014 | swift | //
// StkCharUpxGrLPUpxRM.swift
//
//
// Created by Hugh Bellamy on 06/11/2020.
//
import DataStream
/// [MS-DOC] 2.9.265 StkCharUpxGrLPUpxRM
/// The StkCharUpxGrLPUpxRM structure specifies revision-marking information and formatting for character styles.
public struct StkCharUpxGrLPUpxRM {
public let lpUpxRm: LPUpxRm
public let lpUpxChpxRM: LPUpxChpxRM
public init(dataStream: inout DataStream, size: Int) throws {
let startPosition = dataStream.position
/// lpUpxRm (8 bytes): An LPUpxRm structure that specifies the revision-marking information for the style.
self.lpUpxRm = try LPUpxRm(dataStream: &dataStream)
/// lpUpxChpxRM (variable): An LPUpxChpxRM that specifies the character formatting properties for the revision-marked style formatting.
self.lpUpxChpxRM = try LPUpxChpxRM(dataStream: &dataStream)
if dataStream.position - startPosition != size {
throw OfficeFileError.corrupted
}
}
}
| [
-1
] |
a504aa53ed080b7ab4abb66fa927bfc119776534 | 2f470afd3fe8f7fdd64badad297460602054ba90 | /Sources/PerfectLib/File.swift | 2c570c0f1a9d727d728d215eb49b23fca0e53f83 | [
"Apache-2.0"
] | permissive | sverrisson/Perfect | 4e7ef11702ce1d8aa7195405c864170a6f3c04b4 | 0075c422728a07f95cee474bef3cf972f750a49f | refs/heads/master | 2020-12-25T10:14:10.250325 | 2016-07-04T18:36:20 | 2016-07-04T18:36:20 | 62,581,613 | 0 | 0 | null | 2016-07-04T18:37:24 | 2016-07-04T18:37:20 | Swift | UTF-8 | Swift | false | false | 15,102 | swift | //
// File.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/7/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
#if os(Linux)
import SwiftGlibc
import LinuxBridge
// !FIX! these are obviously sketchy
// I hope SwiftGlibc to eventually include these
// Otherwise, export them from LinuxBridge
let S_IRGRP = (S_IRUSR >> 3)
let S_IWGRP = (S_IWUSR >> 3)
let S_IRWXU = (__S_IREAD|__S_IWRITE|__S_IEXEC)
let S_IRWXG = (S_IRWXU >> 3)
let S_IRWXO = (S_IRWXG >> 3)
let SEEK_CUR: Int32 = 1
let EXDEV = Int32(18)
let EACCES = Int32(13)
let EAGAIN = Int32(11)
let F_OK: Int32 = 0
#else
import Darwin
#endif
let fileCopyBufferSize = 16384
/// Provides access to a file on the local file system
public class File {
var fd = -1
var internalPath = ""
/// Checks that the file exists on the file system
/// - returns: True if the file exists or false otherwise
public var exists: Bool {
return access(internalPath, F_OK) != -1
}
/// Returns true if the file has been opened
public var isOpen: Bool {
return fd != -1
}
/// Returns the file's path
public var path: String { return internalPath }
/// Returns the file path. If the file is a symbolic link, the link will be resolved.
public var realPath: String {
let maxPath = 2048
guard isLink else {
return internalPath
}
var ary = [UInt8](repeating: 0, count: maxPath)
let buffer = UnsafeMutablePointer<Int8>(ary)
let res = readlink(internalPath, buffer, maxPath)
guard res != -1 else {
return internalPath
}
ary.removeLast(maxPath - res)
let trailPath = UTF8Encoding.encode(bytes: ary)
let lastChar = trailPath[trailPath.startIndex]
guard lastChar != "/" && lastChar != "." else {
return trailPath
}
return internalPath.stringByDeletingLastPathComponent + "/" + trailPath
}
/// Returns the modification date for the file in the standard UNIX format of seconds since 1970/01/01 00:00:00 GMT
/// - returns: The date as Int
public var modificationTime: Int {
var st = stat()
let res = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard res == 0 else {
return Int.max
}
#if os(Linux)
return Int(st.st_mtim.tv_sec)
#else
return Int(st.st_mtimespec.tv_sec)
#endif
}
/// Create a file object given a path and open mode
/// - parameter path: Path to the file which will be accessed
/// - parameter fd: The file descriptor, if any, for an already opened file
public init(_ path: String, fd: Int32 = -1) {
self.internalPath = path
self.fd = Int(fd)
}
/// Closes the file if it had been opened
public func close() {
if fd != -1 {
#if os(Linux)
_ = SwiftGlibc.close(CInt(fd))
#else
_ = Darwin.close(CInt(fd))
#endif
fd = -1
}
}
/// Resets the internal file descriptor, leaving the file opened if it had been.
public func abandon() {
fd = -1
}
}
public extension File {
/// The open mode for the file.
public enum OpenMode {
/// Opens the file for read-only access.
case read
/// Opens the file for write-only access, creating the file if it did not exist.
case write
/// Opens the file for read-write access, creating the file if it did not exist.
case readWrite
/// Opens the file for read-write access, creating the file if it did not exist and moving the file marker to the end.
case append
/// Opens the file for read-write access, creating the file if it did not exist and setting the file's size to zero.
case truncate
var toMode: Int {
switch self {
case .read: return Int(O_RDONLY)
case .write: return Int(O_WRONLY|O_CREAT)
case .readWrite: return Int(O_RDWR|O_CREAT)
case .append: return Int(O_RDWR|O_APPEND|O_CREAT)
case .truncate: return Int(O_RDWR|O_TRUNC|O_CREAT)
}
}
}
/// Opens the file using the given mode.
/// - throws: `PerfectError.FileError`
public func open(_ mode: OpenMode = .read) throws {
if fd != -1 {
close()
}
#if os(Linux)
let openFd = linux_open(internalPath, CInt(mode.toMode), mode_t(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))
#else
let openFd = Darwin.open(internalPath, CInt(mode.toMode), mode_t(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))
#endif
guard openFd != -1 else {
try ThrowFileError()
}
fd = Int(openFd)
}
}
public extension File {
/// The current file read/write position.
public var marker: Int {
/// Returns the value of the file's current position marker
get {
if isOpen {
return Int(lseek(Int32(self.fd), 0, SEEK_CUR))
}
return 0
}
/// Sets the file's position marker given the value as measured from the begining of the file.
set {
lseek(Int32(self.fd), off_t(newValue), SEEK_SET)
}
}
}
public extension File {
/// Closes and deletes the file
public func delete() {
close()
unlink(path)
}
/// Moves the file to the new location, optionally overwriting any existing file
/// - parameter path: The path to move the file to
/// - parameter overWrite: Indicates that any existing file at the destination path should first be deleted
/// - returns: Returns a new file object representing the new location
/// - throws: `PerfectError.FileError`
public func moveTo(path: String, overWrite: Bool = false) throws -> File {
let destFile = File(path)
if destFile.exists {
guard overWrite else {
throw PerfectError.fileError(-1, "Can not overwrite existing file")
}
destFile.delete()
}
close()
let res = rename(self.path, path)
if res == 0 {
return destFile
}
if errno == EXDEV {
_ = try self.copyTo(path: path, overWrite: overWrite)
self.delete()
return destFile
}
try ThrowFileError()
}
/// Copies the file to the new location, optionally overwriting any existing file
/// - parameter path: The path to copy the file to
/// - parameter overWrite: Indicates that any existing file at the destination path should first be deleted
/// - returns: Returns a new file object representing the new location
/// - throws: `PerfectError.FileError`
@discardableResult
public func copyTo(path pth: String, overWrite: Bool = false) throws -> File {
let destFile = File(pth)
if destFile.exists {
guard overWrite else {
throw PerfectError.fileError(-1, "Can not overwrite existing file")
}
destFile.delete()
}
let wasOpen = self.isOpen
let oldMarker = self.marker
if !wasOpen {
try open()
} else {
_ = marker = 0
}
defer {
if !wasOpen {
close()
} else {
_ = marker = oldMarker
}
}
try destFile.open(.truncate)
var bytes = try self.readSomeBytes(count: fileCopyBufferSize)
while bytes.count > 0 {
try destFile.write(bytes: bytes)
bytes = try self.readSomeBytes(count: fileCopyBufferSize)
}
destFile.close()
return destFile
}
}
public extension File {
/// Returns the size of the file in bytes
public var size: Int {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return 0
}
return Int(st.st_size)
}
/// Returns true if the file is a symbolic link
public var isLink: Bool {
var st = stat()
let statRes = lstat(internalPath, &st)
guard statRes != -1 else {
return false
}
let mode = st.st_mode
return (Int32(mode) & Int32(S_IFMT)) == Int32(S_IFLNK)
}
/// Returns true if the file is actually a directory
public var isDir: Bool {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return false
}
let mode = st.st_mode
return (Int32(mode) & Int32(S_IFMT)) == Int32(S_IFDIR)
}
/// Returns the UNIX style permissions for the file
public var perms: Int {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return 0
}
let mode = st.st_mode
return Int(Int32(mode) ^ Int32(S_IFMT))
}
}
public extension File {
/// Reads up to the indicated number of bytes from the file
/// - parameter count: The maximum number of bytes to read
/// - returns: The bytes read as an array of UInt8. May have a count of zero.
/// - throws: `PerfectError.FileError`
public func readSomeBytes(count: Int) throws -> [UInt8] {
if !isOpen {
try open()
}
func sizeOr(_ value: Int) -> Int {
var st = stat()
let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st)
guard statRes != -1 else {
return 0
}
if (Int32(st.st_mode) & Int32(S_IFMT)) == Int32(S_IFREG) {
return Int(st.st_size)
}
return value
}
let bSize = min(count, sizeOr(count))
var ary = [UInt8](repeating: 0, count: bSize)
let ptr = UnsafeMutablePointer<UInt8>(ary)
let readCount = read(CInt(fd), ptr, bSize)
guard readCount >= 0 else {
try ThrowFileError()
}
if readCount < bSize {
ary.removeLast(bSize - readCount)
}
return ary
}
/// Reads the entire file as a string
public func readString() throws -> String {
let bytes = try self.readSomeBytes(count: self.size)
return UTF8Encoding.encode(bytes: bytes)
}
}
public extension File {
/// Writes the string to the file using UTF-8 encoding
/// - parameter s: The string to write
/// - returns: Returns the number of bytes which were written
/// - throws: `PerfectError.FileError`
@discardableResult
public func write(string: String) throws -> Int {
return try write(bytes: Array(string.utf8))
}
/// Write the indicated bytes to the file
/// - parameter bytes: The array of UInt8 to write.
/// - parameter dataPosition: The offset within `bytes` at which to begin writing.
/// - parameter length: The number of bytes to write.
/// - throws: `PerfectError.FileError`
@discardableResult
public func write(bytes: [UInt8], dataPosition: Int = 0, length: Int = Int.max) throws -> Int {
let len = min(bytes.count - dataPosition, length)
let ptr = UnsafeMutablePointer<UInt8>(bytes).advanced(by: dataPosition)
#if os(Linux)
let wrote = SwiftGlibc.write(Int32(fd), ptr, len)
#else
let wrote = Darwin.write(Int32(fd), ptr, len)
#endif
guard wrote == len else {
try ThrowFileError()
}
return wrote
}
}
public extension File {
/// Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will block the current thread until the lock can be performed.
/// - parameter byteCount: The number of bytes to lock
/// - throws: `PerfectError.FileError`
public func lock(byteCount: Int) throws {
if !isOpen {
try open(.write)
}
let res = lockf(Int32(self.fd), F_LOCK, off_t(byteCount))
guard res == 0 else {
try ThrowFileError()
}
}
/// Unlocks the number of bytes starting from the current position marker up to the indicated byte count.
/// - parameter byteCount: The number of bytes to unlock
/// - throws: `PerfectError.FileError`
public func unlock(byteCount: Int) throws {
if !isOpen {
try open(.write)
}
let res = lockf(Int32(self.fd), F_ULOCK, off_t(byteCount))
guard res == 0 else {
try ThrowFileError()
}
}
/// Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will throw an exception if the file is already locked, but will not block the current thread.
/// - parameter byteCount: The number of bytes to lock
/// - throws: `PerfectError.FileError`
public func tryLock(byteCount: Int) throws {
if !isOpen {
try open(.write)
}
let res = lockf(Int32(self.fd), F_TLOCK, off_t(byteCount))
guard res == 0 else {
try ThrowFileError()
}
}
/// Tests if the indicated bytes are locked
/// - parameter byteCount: The number of bytes to test
/// - returns: True if the file is locked
/// - throws: `PerfectError.FileError`
public func testLock(byteCount: Int) throws -> Bool {
if !isOpen {
try open(.write)
}
let res = Int(lockf(Int32(self.fd), F_TEST, off_t(byteCount)))
guard res == 0 || res == Int(EACCES) || res == Int(EAGAIN) else {
try ThrowFileError()
}
return res != 0
}
}
// Subclass to represent a file which can not be closed
private final class UnclosableFile : File {
override init(_ path: String, fd: Int32) {
super.init(path, fd: fd)
}
override func close() {
// nothing
}
}
/// A temporary, randomly named file.
public final class TemporaryFile: File {
/// Create a temporary file, usually in the system's /tmp/ directory
/// - parameter withPrefix: The prefix for the temporary file's name. Random characters will be appended to the file's eventual name.
public convenience init(withPrefix: String) {
let template = withPrefix + "XXXXXX"
let utf8 = template.utf8
let name = UnsafeMutablePointer<Int8>(allocatingCapacity: utf8.count + 1)
var i = utf8.startIndex
for index in 0..<utf8.count {
name[index] = Int8(utf8[i])
i = utf8.index(after: i)
}
name[utf8.count] = 0
let fd = mkstemp(name)
let tmpFileName = String(validatingUTF8: name)!
name.deallocateCapacity(utf8.count + 1)
self.init(tmpFileName, fd: fd)
}
}
/// This file can be used to write to standard in
public var fileStdin: File {
return UnclosableFile("/dev/stdin", fd: STDIN_FILENO)
}
/// This file can be used to write to standard out
public var fileStdout: File {
return UnclosableFile("/dev/stdout", fd: STDOUT_FILENO)
}
/// This file can be used to write to standard error
public var fileStderr: File {
return UnclosableFile("/dev/stderr", fd: STDERR_FILENO)
}
| [
-1
] |
e620d277d4730f4a332bd1dba8090ca0f7cf7edb | 1bb4576c683bf648b710e555b504b5426b92e49b | /KXSample-MasteriOS/View/ViewCatalog/ViewCatalog/SystemViews/ContentViews/ImageView/ImageAnimationViewController.swift | d4cc75d46e11c419a604aca9a2041c560740c42a | [
"MIT"
] | permissive | nakg/MasteringiOS | 33c4ec60403bcd0a064353fe12291e24253ceab0 | a375af1917276e635277a2a0b806177b07d52fe8 | refs/heads/master | 2022-12-07T20:20:55.015442 | 2020-08-22T15:37:49 | 2020-08-22T15:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,707 | swift | //
// Copyright (c) 2018 KxCoding <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class ImageAnimationViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBAction func startAnimation(_ sender: Any) {
imageView.startAnimating()
}
@IBAction func stopAnimation(_ sender: Any) {
if imageView.isAnimating {
imageView.stopAnimating()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let images = (0...3).compactMap{ UIImage(named: "phone-ring\($0)") }
imageView.animationImages = images
imageView.animationDuration = 1
imageView.animationRepeatCount = 5
}
}
| [
194560,
395267,
196612,
395271,
395274,
108279,
395278,
395280,
395281,
395282,
395283,
407569,
108281,
395286,
395287,
395289,
395290,
196638,
395295,
395296,
196641,
98341,
61478,
98344,
98345,
98349,
174135,
354359,
124987,
174139,
354364,
229438,
124988,
229440,
229441,
395328,
229443,
174148,
229444,
395332,
327751,
174152,
395333,
395334,
378951,
229449,
174159,
229456,
112721,
106580,
106582,
106584,
106585,
106586,
106587,
112730,
174171,
125048,
229504,
125057,
125064,
125065,
235658,
125066,
229524,
303255,
303256,
125087,
215205,
215206,
215208,
215211,
215212,
215215,
241846,
241852,
241859,
241862,
317638,
241864,
317640,
241866,
241868,
241870,
241873,
262353,
241877,
241878,
262359,
241879,
106713,
106714,
262366,
106720,
106725,
241894,
241897,
241901,
241903,
241904,
176370,
241907,
241908,
176373,
241910,
260342,
106742,
176378,
241916,
141565,
141566,
141569,
241923,
241928,
141577,
141578,
241930,
141576,
241931,
241934,
141583,
241936,
241937,
141586,
141588,
12565,
227604,
227607,
241944,
227608,
12569,
141593,
141594,
141595,
141596,
141597,
141598,
141599,
141600,
227610,
141603,
241952,
241957,
141606,
141607,
141608,
289062,
241962,
289067,
141612,
289068,
141609,
12592,
241961,
289074,
241963,
97347,
289078,
141627,
141629,
141632,
141634,
241989,
227609,
213319,
141640,
141641,
141642,
141643,
213320,
241992,
241996,
241998,
241999,
262475,
242002,
141651,
141646,
227612,
242006,
141655,
215384,
282967,
227613,
141650,
141660,
168285,
282969,
141663,
141664,
227614,
141670,
172391,
141674,
141677,
141679,
141681,
375154,
190840,
190841,
430456,
190843,
190844,
430458,
190842,
375165,
375168,
141700,
375172,
141702,
141701,
430471,
141707,
430476,
430475,
141711,
430483,
217492,
217494,
197016,
197018,
197019,
197021,
295330,
295331,
197029,
430502,
168359,
303550,
160205,
160208,
381398,
305638,
272872,
223741,
61971,
191006,
191007,
272931,
57893,
272934,
57896,
328232,
420394,
57899,
57900,
295467,
57903,
57904,
57905,
57906,
158257,
336445,
336446,
336450,
336451,
336454,
336455,
336457,
336460,
336465,
55890,
336466,
336469,
336470,
336471,
336472,
336473,
336474,
336478,
336479,
336480,
336481,
336482,
336483,
111202,
272994,
336488,
336489,
273003,
273021,
273023,
437305,
297615,
297620,
437310,
297625,
297636,
437314,
135854,
135861,
242361,
244419,
244421,
66247,
244427,
248524,
127693,
244430,
66257,
66261,
127702,
127703,
62174,
334562,
127716,
334564,
62183,
127727,
127729,
244469,
244470,
318199,
318200,
142073,
164601,
316155,
142076,
228510,
334590,
318207,
244480,
334591,
142083,
334596,
142087,
334600,
318218,
334603,
318220,
334602,
334606,
318223,
334607,
334604,
142095,
318228,
318231,
318233,
318234,
318236,
318237,
318239,
318241,
187173,
187174,
187175,
318246,
187177,
187178,
187179,
187180,
314167,
316216,
396088,
396089,
396091,
396092,
241955,
396094,
148287,
316224,
396095,
396098,
314179,
279367,
396104,
396110,
396112,
396114,
396115,
396118,
396119,
396120,
396122,
396123,
396125,
396126,
396127,
396128,
396129,
299880,
396137,
162668,
299884,
187248,
396147,
396151,
248696,
396153,
187258,
187259,
322430,
437356,
60304,
60318,
60322,
60323,
185258,
185259,
60331,
23469,
185262,
23470,
23472,
23473,
23474,
23475,
23476,
185267,
213935,
23479,
60337,
287674,
23483,
23487,
185280,
281538,
281539,
23492,
23494,
185286,
228306,
23508,
23515,
23517,
40089,
23523,
23531,
203755,
23533,
341058,
152560,
23552,
171008,
40096,
23559,
437256,
23561,
437258,
40098,
23572,
437269,
23574,
23575,
437273,
23580,
23581,
40101,
23585,
437281,
23590,
23591,
23594,
23596,
23599,
189488,
97327,
187442,
189490,
187444,
189492,
189493,
187447,
189491,
23601,
97329,
144435,
23607,
144437,
144438,
144441,
97339,
23612,
144442,
144443,
144444,
23616,
144445,
341057,
341060,
222278,
341062,
341063,
341066,
341068,
437326,
40109,
40110,
185428,
285781,
203862,
285782,
312407,
285785,
115805,
115806,
115807,
293982,
115809,
115810,
312413,
437349,
185446,
312423,
115817,
242794,
115819,
115820,
185452,
185454,
115823,
185455,
115825,
242796,
115827,
242803,
115829,
437364,
242807,
437371,
294012,
294016,
205959,
437390,
437392,
437396,
40088,
312473,
189594,
208026,
40092,
208027,
189598,
40095,
208029,
208033,
27810,
228512,
228513,
312476,
312478,
189607,
312479,
189609,
189610,
312482,
189612,
312489,
312493,
437415,
437416,
189617,
312497,
189619,
312498,
189621,
312501,
189623,
437424,
437426,
189626,
437428,
312502,
312504,
437431,
322751,
437433,
437436,
437440,
38081,
437443,
437445,
292041,
292042,
437451,
38092,
437453,
128874,
181455,
292049,
437458,
128875,
152789,
203990,
203991,
152795,
204000,
204003,
339176,
339177,
152821,
208117,
152825,
294137,
294138,
279818,
206094,
279823,
206097,
206098,
294162,
206102,
206104,
206108,
206109,
181533,
425247,
294181,
27943,
181544,
294183,
40105,
27948,
181553,
181559,
173368,
206138,
151285,
173379,
312480,
152906,
152907,
152908,
152909,
152910,
290123,
290125,
290126,
290127,
290130,
3119,
312483,
173394,
290135,
290136,
245081,
290137,
290139,
378206,
378208,
222562,
222563,
222566,
228717,
222573,
228721,
222577,
222579,
222581,
222582,
222587,
222590,
222591,
54655,
222596,
222597,
177543,
222599,
222601,
54666,
222603,
222604,
54669,
222605,
222606,
222607,
54673,
54678,
54680,
279969,
54692,
152998,
54698,
54701,
54703,
153009,
298431,
212420,
370118,
153037,
153049,
153051,
157151,
222689,
222692,
222693,
112111,
112115,
112117,
112120,
40451,
112131,
40453,
280068,
40455,
40458,
40460,
40463,
112144,
112145,
40466,
40469,
40471,
40475,
40477,
40479,
40482,
362020,
362022,
116267,
282156,
34362,
316993,
173634,
173635,
316995,
316997,
173639,
312427,
106085,
319081,
319085,
319088,
319089,
300660,
300661,
300662,
300663,
319094,
319098,
319101,
319103,
394899,
52886,
52887,
394905,
394908,
394910,
394912,
52896,
52899,
52900,
339622,
147115,
151218,
394935,
321210,
292544,
108230,
108234,
296682,
341052,
108240,
34516,
108245,
212694,
296660,
341054,
34522,
341055,
34531,
192230,
192231,
192232,
296681,
34538,
296679,
34540,
34541,
216812,
216814,
216815,
216816,
216818,
216819,
296684,
296687,
216822,
296688,
296691,
296692,
216826,
296698,
216828,
216829,
296699,
296700,
216832,
216833,
216834,
296703,
216836,
216837,
216838,
296707,
296708,
296710,
296712,
296713,
296694,
313101,
276232,
313099,
313104,
276236,
313102,
313108,
313111,
313112,
149274,
149275,
159518,
149280,
159523,
296701,
296704,
321342,
210755,
210756,
210757,
210758,
321353,
218959,
120655,
120656,
218962,
218963,
218964,
223064,
223065,
180058,
229209,
223069,
229213,
169824,
229217,
169826,
292705,
223075,
237413,
169830,
292709,
223076,
128873,
180070,
169835,
128876,
169837,
128878,
223086,
223087,
128881,
128882,
128883,
128884,
227180,
227183,
227188,
141181,
327550,
108419,
141189,
141198,
108431,
108432,
141202,
141208,
219033,
108448,
219040,
141219,
219043,
219044,
141220,
141223,
141228,
141229,
108460,
108462,
229294,
229295,
141235,
319426,
141253,
319432,
141264,
59349,
141272,
141273,
40931,
40932,
141284,
141290,
40940,
40941,
141293,
141295,
174063,
231406,
174066,
174067,
237559,
174074,
395259,
194559
] |
c6d1cc3411a3300a01347b314a505342bb80a07d | 354db43539711667a4cb38ab192a6bfb43e0b6db | /OmniNews/Shared/Model/Article/Vignette.swift | de66e62ebd933378d9b6d90d59b329f50667cff3 | [
"Apache-2.0"
] | permissive | Kamajabu/SchibstedOmniNews | b8e4d2bfe185d48fe56ddf06592cf0beaf833da2 | 13cf224756db845fa745ab3fdc50148d909edba9 | refs/heads/master | 2021-07-11T12:44:21.654476 | 2020-10-17T14:02:24 | 2020-10-17T14:02:24 | 213,393,171 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 276 | swift | //
// Vignette.swift
// OmniNews
//
// Created by Kamil Buczel on 07/10/2019.
// Copyright © 2019 Kamajabu. All rights reserved.
//
import Foundation
struct Vignette: Codable {
let title: String?
enum CodingKeys: String, CodingKey {
case title
}
}
| [
-1
] |
2edf029109cfad15b4cdd20fd20f70c1e08835f5 | 62c6eca45e0395dfbc68e0b6df05752a2c4de9dc | /SwiftXcode/TopologicalSort.swift | 4fbef872493b9d9cedf93993b4379904f4910421 | [] | no_license | ricktang1991/Swift | af9ff1ee648b183ccff9fd161fc5102b922e3ce0 | 7e5a5f8d829c660ea2b6a5c329963f14a9cf9b10 | refs/heads/master | 2021-02-05T18:36:19.599419 | 2020-03-19T20:30:23 | 2020-03-19T20:30:23 | 243,816,224 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,176 | swift | //
// TopologicalSort.swift
// SwiftXcode
//
// Created by 桑染 on 2020-03-03.
// Copyright © 2020 Rick. All rights reserved.
//
import Foundation
func TopologicalSort() {
let firstline = readLine()!
.split(separator: " ")
.map { Int($0)! }
let N = firstline[0]
let M = firstline[1]
var adj = [[Int]](repeating: [Int](), count: N + 1)
var indegree = [Int](repeating: 0, count: N + 1)
for _ in 0..<M { // M edges
let edge = readLine()!
.split(separator: " ")
.map { Int($0)! }
let u = edge[0]
let v = edge[1]
adj[u].append(v)
indegree[v] += 1
}
// topological sort
let q = Queue<Int>()
// initial state
for v in 1...N {
if indegree[v] == 0 {
q.enqueue(item: v)
}
}
// BFS
while !q.isEmpty() {
let x = q.dequeue()!
print(x) // process
for v in adj[x] {
indegree[v] -= 1 // decrement indegree
if indegree[v] == 0 {
q.enqueue(item: v)
}
}
}
}
| [
-1
] |
46a9a9b64e7a327cd425542278ff3622db9a9091 | 88544a70e6c8e44a344d39c763f37cc9dfc969eb | /PawnStars-iOS/PawnStars-iOS/ViewModel/Flex/FlexDetailContentViewModel.swift | 0080c46e32285f984d6ae07b23fc76f786bd94ee | [
"MIT"
] | permissive | team-pawn-stars/PawnStars-iOS | e40007f7b5ceea22a083607060101af71a10429c | 8e885ca0bfd86e1bdbaa0f083d7f1affa944436f | refs/heads/master | 2020-05-02T10:25:46.974513 | 2019-06-14T00:01:18 | 2019-06-14T00:01:18 | 177,896,439 | 1 | 1 | MIT | 2019-06-13T23:58:39 | 2019-03-27T01:32:59 | Swift | UTF-8 | Swift | false | false | 966 | swift | //
// FlexDetailContentViewModel.swift
// PawnStars-iOS
//
// Created by daeun on 23/05/2019.
// Copyright © 2019 PawnStars. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
class FlexDetailContentViewModel: ViewModelType {
struct Input {
let imageUrl: BehaviorRelay<String>
}
struct Output {
let imageData: Driver<Data>
}
func transform(input: Input) -> Output {
let imageData = input.imageUrl.flatMapLatest { url -> Observable<Data> in
do {
let url = URL(string: "http://whale.istruly.sexy:3214\(url)")
let data = try Data(contentsOf: url!)
return Observable.of(data)
}catch let err {
print("Error : \(err.localizedDescription)")
}
return Observable.of(Data())
}
return Output(imageData: imageData.asDriver(onErrorJustReturn: Data()))
}
}
| [
-1
] |
bfd52205e7cbeb8306b91d31b459b167fed911d4 | 8bbceae99490a685e781e04e49ed1c04e3d5f909 | /pocketgallery/TemporaryMenuViewController.swift | 6d9c3a64faf0ad476967236b37cc1101ba9283c4 | [] | no_license | renaz6/pocketgallery | 2614fac4a71d861932f3aecfe593194fae6244b0 | 90a6ddd268fbe890db763aaaf10ad54eb8be5dec | refs/heads/main | 2023-03-29T00:05:26.264663 | 2021-04-06T18:59:45 | 2021-04-06T18:59:45 | 355,296,998 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 9,862 | swift | //
// TemporaryMenuViewController.swift
// pocketgallery
//
// Created by Serena Zamarripa on 10/16/20.
// Copyright © 2020 zamarripa. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore
protocol NotLoggedIn {
func isLogged(withDisplayName: String?)
}
class TemporaryMenuViewController: UIViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var logoutOutlet: UIButton!
@IBOutlet weak var loginRegisterButton: UIButton!
@IBOutlet weak var repeatPassword: UITextField!
@IBOutlet weak var loginRegisterSegmentedControl: UISegmentedControl!
@IBAction func valueChanged(_ sender: Any) {
changeInterfaceAccoringto(loginRegisterSegmentedControl.selectedSegmentIndex)
}
private var loggedIn = false
var delegate: UIViewController!
var logInDelegate: UIViewController!
var settingsDelegate: UIViewController!
var theMessage = ""
private var displayName = ""
var firestore = Firestore.firestore()
@objc func handleLogin() {
Auth.auth().signIn(withEmail: self.emailField.text!, password: self.passwordField.text!) { user, error in
if let error = error, user == nil {
let alert = UIAlertController(
title: "Sign in failed",
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title:"OK",style:.default))
self.present(alert, animated: true, completion: nil)
} else {
print("Login Successful!")
let alert = UIAlertController(
title: "Sign in Successful!",
message: "Welcome.",
preferredStyle: .alert)
if self.logInDelegate != nil {
let otherVC = self.logInDelegate as! NotLoggedIn
otherVC.isLogged(withDisplayName: self.nameField.text)
}
alert.addAction(UIAlertAction(title:"OK",style:.default))
self.present(alert, animated: true, completion: nil)
if let navigator = self.navigationController {
navigator.popViewController(animated: true)
}
}
}
}
@objc func handleRegister(){
guard let email = emailField.text,
let password = passwordField.text,
let repeatPass = repeatPassword.text,
email.count > 0,
password.count > 0,
repeatPass.count > 0
else {
return
}
if password == repeatPass {
Auth.auth().createUser(withEmail: email, password: password) { user, error in
if error == nil, let userInfo = user {
// add display name
let changeRequest = userInfo.user.createProfileChangeRequest()
changeRequest.displayName = self.nameField.text
changeRequest.commitChanges { error in
print("Error setting display name: ", error ?? "")
}
// create entry (saved events) in database
self.firestore.collection("users").document(userInfo.user.uid).setData(["savedWorks": []])
if self.delegate != nil {
let otherVC = self.delegate as! LogIn
otherVC.signedIn(withDisplayName: self.emailField.text)
}
if self.logInDelegate != nil {
let otherVC = self.logInDelegate as! NotLoggedIn
otherVC.isLogged(withDisplayName: self.emailField.text)
self.theMessage = "You will be returned to My Events."
}
if self.settingsDelegate != nil {
let otherVC = self.settingsDelegate as! LoggedIn
self.theMessage = "You will be returned to Settings."
otherVC.isNowSignedIn(withDisplayName: self.emailField.text)
}
self.view.endEditing(false)
let alert = UIAlertController(
title: "Sign Up Successful",
message: self.theMessage,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title:"OK", style: .default) { action in
// return them to the last screen
if let navigator = self.navigationController {
navigator.popViewController(animated: true)
}
})
self.present(alert, animated: true)
} else {
let alert = UIAlertController(
title: "Error",
message: error?.localizedDescription,
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
}
} else {
let alert = UIAlertController(
title: "Passwords do not match",
message: "Please make sure passwords are the same",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
Auth.auth().addStateDidChangeListener { auth, user in
self.loggedIn = (user != nil)}
changeInterfaceAccoringto(loginRegisterSegmentedControl.selectedSegmentIndex)
}
override func viewWillAppear(_ animated: Bool) {
if(!loggedIn){
logoutOutlet.isHidden = true
}
else{
loginRegisterSegmentedControl.isHidden = true
loginRegisterButton.isHidden = true
nameField.isHidden = true
emailField.isHidden = true
passwordField.isHidden = true
}
}
func changeInterfaceAccoringto(_ index:Int){
/*Remove all targets before add*/
loginRegisterButton.removeTarget(nil, action: nil, for: .allEvents)
switch index {
case 0:
nameField.isHidden = true
repeatPassword.isHidden = true
loginRegisterButton.setTitle("Login", for: UIControl.State())
loginRegisterButton.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
case 1:
nameField.isHidden = false
repeatPassword.isHidden = false
loginRegisterButton.setTitle("Register", for: UIControl.State())
loginRegisterButton.addTarget(self, action: #selector(handleRegister), for: .touchUpInside)
default:
break;
}
}
@IBAction func savedButtonClicked(_ sender: Any) {
}
@IBAction func settingsButtonClicked(_ sender: Any) {
do {
try Auth.auth().signOut()
} catch {
print(error)
}
navigationController?.popViewController(animated: true)
let alert = UIAlertController(
title: "Update",
message: "Logout succesful.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Return to home.", style: .default, handler: { action in self.performSegue(withIdentifier: "menuToHome", sender: self) }))
self.present(alert, animated: true)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toSavedSegue"
{
if(loggedIn){
let dest = segue.destination as? SavedViewController
}
else{
let alert = UIAlertController(
title: "Forbidden",
message: "Please sign-in to access saved items.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
}
else if segue.identifier == "toSettingsSegue"
{
if(loggedIn){
let dest = segue.destination as? SettingsViewController
}
else{
let alert = UIAlertController(
title: "Forbidden",
message: "Please sign-in to access settings.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
}
}
// code to dismiss keyboard when user clicks on background
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func isLogged(withDisplayName: String?) {
if (delegate != nil) {
let otherVC = self.delegate as! LogIn
otherVC.signedIn(withDisplayName: displayName)
}
}
}
| [
-1
] |
7955b42cfc9065d20265a7c5b16fce09a80e1d3c | 323dd0cfda1e0ddc6dab5ee8e77ba7d2aa3fb481 | /SideMenuSample/MainContainerModule/Router/MainContainerRouter.swift | 0abbb2bf314f81ca879778f1c240183b18517acf | [
"MIT"
] | permissive | CybercomPoland/ViperSideDrawer | 119676aeeeb49065fe505d174bd414d20e2518ef | 955a1b383d4a43e55200759945fa9d549062f6dd | refs/heads/master | 2020-12-02T17:47:01.249262 | 2018-04-20T09:29:22 | 2018-04-20T09:29:22 | 96,426,482 | 0 | 1 | null | 2017-11-17T11:07:04 | 2017-07-06T12:12:39 | Swift | UTF-8 | Swift | false | false | 939 | swift | //
// MainContainerRouter.swift
// ViperSideDrawer
//
// Created by Aleksander Maj on 30/06/2017.
// Copyright © 2017 Aleksander Maj. All rights reserved.
//
import UIKit
import ViperSideDrawer
extension MainContainerRouter: MainContainerRouterInterface {
func presentSideMenu(with delegate: SideMenuModuleDelegate?, swipeInteractionController: SwipeInteractionController? = nil) {
SideMenuRouter.presentUserInterface(from: viewController, with: delegate, percentInteractiveTransition: swipeInteractionController?.percentInteractiveTransition)
}
func embedInitialModule(in containerModule: MenuOptionDelegate) {
embedModule1(in: containerModule)
}
func embedModule1(in containerModule: MenuOptionDelegate) {
MainOption1Router.embed(in: containerModule)
}
func embedModule2(in containerModule: MenuOptionDelegate) {
MainOption2Router.embed(in: containerModule)
}
}
| [
-1
] |
585f4bb6249f06c2ec64932e27f1074ffc73d38e | 596fb56fb87a506e54e665536553ecc28388c29a | /TouristSites/View/ViewController/MainViewController.swift | 7e541fdfa6f616162abc84894451dbfbf85bd5bb | [] | no_license | littlema0404/TouristSites | e68d51601b40e3e48aa539576bc52f2338680240 | 5ca363838ada450b66b1020ca2d099f45cf24d69 | refs/heads/master | 2020-08-30T14:07:57.313336 | 2019-12-17T06:29:03 | 2019-12-17T06:29:03 | 218,404,186 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 7,395 | swift | //
// ViewController.swift
// TouristSites
//
// Created by littlema on 2019/10/31.
// Copyright © 2019 littema. All rights reserved.
//
import UIKit
enum MainViewState: Equatable {
case normal(isEnd: Bool)
case empty
case loading(isLoadMore: Bool)
case apiError
case internetError(isInit: Bool)
}
protocol MainViewControllerCoordinatorDelegate: AnyObject {
func showDetailFrom(_ viewController: UIViewController, viewModel: DetailViewModel)
}
class MainViewController: UIViewController {
weak var coordinator: MainViewControllerCoordinatorDelegate?
let viewModel: MainViewModel
let monitor = NetworkMonitor()
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .backgroundGray
tableView.separatorStyle = .none
tableView.dataSource = self
tableView.delegate = self
tableView.registerWithNib(identifier: MainTableViewCell.identifier)
return tableView
}()
lazy var indicatorView: UIActivityIndicatorView = {
let indicatorView = UIActivityIndicatorView(style: .medium)
indicatorView.hidesWhenStopped = true
indicatorView.startAnimating()
return indicatorView
}()
lazy var footerView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
let indicatorView = UIActivityIndicatorView(style: .medium)
indicatorView.hidesWhenStopped = true
view.addSubview(indicatorView)
indicatorView.addConstraintCenterXYOf(view)
indicatorView.startAnimating()
return view
}()
lazy var errorDescLabel: UILabel = {
let label = UILabel()
label.textColor = .stringGray
return label
}()
init(viewModel: MainViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupBinding()
setupInternetListening()
}
private func setupView() {
title = "台北市熱門景點"
view.backgroundColor = .backgroundGray
navigationItem.backBarButtonItem = UIBarButtonItem()
navigationItem.backBarButtonItem?.title = ""
view.addSubview(tableView)
tableView.addConstrainSameWith(self.view)
tableView.tableFooterView = footerView
view.addSubview(indicatorView)
indicatorView.addConstraintCenterXYOf(self.view)
view.addSubview(errorDescLabel)
errorDescLabel.addConstraintCenterXYOf(self.view)
}
private func setupBinding() {
viewModel.cellViewModels.addObserver { [weak self] (newViewModels, oldViewModels) in
var indexPaths = [IndexPath]()
for index in oldViewModels.count..<newViewModels.count {
indexPaths.append(IndexPath(row: index, section: 0))
}
self?.tableView.insertRows(at: indexPaths, with: .automatic)
}
viewModel.state.addObserver { [weak self] state in
DispatchQueue.main.async {
switch state {
case .normal(let isEnd):
self?.showTableView(isEnd: isEnd)
case .empty:
self?.showInfoLabel(text: "尚無資料...")
case .loading(let isLoadMore):
isLoadMore ? nil : self?.showIndicator()
case .apiError:
self?.showInfoLabel(text: "系統發生異常...")
case .internetError(let isInit):
if isInit {
self?.showInfoLabel(text: "網路連線異常...")
} else {
self?.showAlertController(title: "網路無法連線...", message: "請確認網路環境!")
}
}
}
}
}
private func setupInternetListening() {
monitor.startMonitoring { [weak self] (connection, reachable) in
if reachable == .yes {
self?.viewModel.fetchData()
} else {
let isInit = self?.viewModel.numberOfCellViewModels == 0
self?.viewModel.state.value = .internetError(isInit: isInit)
}
}
viewModel.fetchData()
}
private func showTableView(isEnd: Bool) {
tableView.isHidden = false
errorDescLabel.isHidden = true
indicatorView.isHidden = true
footerView.isHidden = isEnd
}
private func showInfoLabel(text: String) {
tableView.isHidden = true
errorDescLabel.isHidden = false
errorDescLabel.text = text
indicatorView.isHidden = true
}
private func showIndicator() {
tableView.isHidden = true
errorDescLabel.isHidden = true
indicatorView.isHidden = false
}
private func showAlertController(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancel = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
}
extension MainViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfCellViewModels
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MainTableViewCell.identifier, for: indexPath)
guard let touristSiteCell = cell as? MainTableViewCell else { return cell }
let cellViewModel = viewModel.getViewModel(index: indexPath.row)
touristSiteCell.viewModel = cellViewModel
let detailViewModel = viewModel.getDetailViewModel(index: indexPath.row)
touristSiteCell.tapCollectionViewCellHandler = { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.coordinator?.showDetailFrom(strongSelf, viewModel: detailViewModel)
}
touristSiteCell.photoCollectionView.reloadData()
return touristSiteCell
}
}
extension MainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView,
willDisplay cell: UITableViewCell,
forRowAt indexPath: IndexPath) {
cell.alpha = 0
let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeInOut, animations: {
cell.alpha = 1
})
animator.startAnimation()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > (scrollView.contentSize.height - UIScreen.main.bounds.height) {
self.viewModel.fetchData()
}
}
}
| [
-1
] |
2be318cccbfc1c20cf047c05a2bea8426bc6e18d | a2363e36b38dad63a20c0f8e07fc313ac45449db | /ManyFiles/R/R60.swift | f587fbbe66c819f2e7f97e069650c139f3d62d85 | [] | no_license | chkpnt/ManyFiles | 5099224d1354e82212392364dba3963ba2898b1a | 0d2f93408099b0078d055e90e26347432ae228e9 | refs/heads/master | 2021-05-11T01:18:22.123331 | 2018-01-21T18:55:34 | 2018-01-21T18:55:34 | 118,326,560 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 116 | swift | import Foundation
class R60 {
func someMethod() -> Int {
return Int(arc4random_uniform(100))
}
}
| [
-1
] |
5a3d6bef0041985993fe6478d350b133d95f08ab | 655f8367d51497d944e819a3bba19768045650c5 | /swift/Carthage/Checkouts/XpringKit/Tests/Helpers/UInt64+Test.swift | 6f2c330d6543dc722df86d9e4847242da8ee2f6d | [
"MIT"
] | permissive | msgpo/deconstructing-defi-demo | 3ad228a85399eabc8581ea7771c268aad37c9539 | 235045d353f68b2cda30ebb1c33c38c198c730a9 | refs/heads/master | 2022-04-10T12:14:11.519537 | 2020-03-07T12:07:34 | 2020-03-07T12:07:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 162 | swift | extension UInt64 {
public static let testBalance: UInt64 = 1_000
public static let testSendAmount: UInt64 = 20
public static let testSequence: UInt64 = 2
}
| [
-1
] |
6a19b506c3dcf23e4799c3cd87fcd3bd9dea04ca | 3255ad422e33f1fdb586a9f215d2cdd4574ac4fa | /EHireProject/EHire/ManagerFeedbackModule/Model/EHManagerialFeedbackModel.swift | 505c2c5a0428268047bf7978bd674ea21ca3b69d | [] | no_license | srilatha-sriram/eHire | 770fa6f195b8ccd77107c2e1ba1250fd1ea74c42 | 3d42d547364ea34c332aa9963254f8d12272a311 | refs/heads/master | 2021-01-16T19:22:31.184756 | 2016-04-14T07:22:14 | 2016-04-14T07:22:14 | 48,106,516 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,429 | swift | //
// ManagerialFeedbackModel.swift
// EHire
//
// Created by Pavithra G. Jayanna on 24/12/15.
// Copyright © 2015 Exilant Technologies. All rights reserved.
//
import Cocoa
class EHManagerialFeedbackModel: NSObject {
var id : Int16?
var commentsOnCandidate: NSAttributedString?
var commentsOnTechnology: NSAttributedString?
var commitments: NSAttributedString?
var grossAnnualSalary: NSNumber?
var managerName: String?
var isCgDeviation: NSNumber?
var jestificationForHire: NSAttributedString?
var modeOfInterview: String?
var ratingOnCandidate: Int16?
var ratingOnTechnical: Int16?
var recommendation: String?
var recommendedCg: String?
var candidate: Candidate?
var skillSet : [SkillSet] = []
var designation: String?
var isSubmitted: NSNumber?
// init(candidateDetails:EHCandidateDetails) {
// self.commentsOnCandidate = ""
// self.commentsOnTechnology = ""
// self.commitments = ""
// self.grossAnnualSalary = 0.0
// self.managerName = ""
// self.isCgDeviation = 0
// self.jestificationForHire = ""
// self.modeOfInterview = ""
// self.ratingOnCandidate = 0
// self.ratingOnTechnical = 0
// self.recommendation = ""
// self.recommendedCg = ""
// self.candidate = candidateDetails
// self.designation = ""
// }
}
| [
-1
] |
0ccdb491b189d1b779496bb7a1f221d30781c7d4 | 978dbcca27e780b615c1613faed0316e6197c2ed | /SearchEngine/Controllers/FilePreviewController.swift | 25d0ab93168165c808ca41dcc6f0474b53b50c6b | [] | no_license | scaraux/SearchEngine | d9497719478f9ba415cf290116dae4e4689c6d53 | 10807b03c5a001951f8a7163f7b9ee7b739e7274 | refs/heads/master | 2020-03-28T19:10:20.485590 | 2020-02-08T02:01:01 | 2020-02-08T02:01:01 | 148,951,348 | 8 | 2 | null | null | null | null | UTF-8 | Swift | false | false | 2,698 | swift | //
// FilePreviewController.swift
// SearchEngine
//
// Created by Oscar Götting on 9/30/18.
// Copyright © 2018 Oscar Götting. All rights reserved.
//
import Cocoa
class FilePreviewController: NSViewController {
@IBOutlet var textView: NSTextView!
var fileDocument: FileDocument?
var queryData: QueryResult?
override func viewDidLoad() {
super.viewDidLoad()
self.textView.isEditable = false
setupText()
}
func getFileData() -> String? {
guard let file = self.queryData?.document else {
return nil
}
do {
return try String(contentsOf: file.fileURL, encoding: String.Encoding.utf8)
}
catch {
fatalError("Cannot read data from file \(file.fileURL)")
}
}
func setupText() {
guard let query = self.queryData else {
return
}
guard let content = getFileData() else {
return
}
let attributes = [NSAttributedString.Key.foregroundColor: NSColor.white]
let attributedContent = NSMutableAttributedString(string: content, attributes: attributes)
let area = NSRange(location: 0, length: attributedContent.length)
let font = NSFont.systemFont(ofSize: 15.0, weight: NSFont.Weight.light)
attributedContent.addAttribute(NSAttributedString.Key.font, value: font, range: area)
for term in query.matchingForTerms {
var range = NSRange(location: 0, length: attributedContent.length)
let inputLength = attributedContent.string.count
let spacedTerm = " " + term + " "
while range.location != NSNotFound {
range = (content as NSString).range(of: spacedTerm,
options: [NSString.CompareOptions.caseInsensitive],
range: range)
if range.location != NSNotFound {
let finalRange = NSRange(location: range.location + 1, length: range.length - 2)
attributedContent.addAttributes([NSAttributedString.Key.foregroundColor: NSColor.black,
NSAttributedString.Key.backgroundColor: NSColor.gray],
range: finalRange)
range = NSRange(location: range.location + range.length,
length: inputLength - (range.location + range.length))
}
}
}
self.textView.textStorage?.append(attributedContent)
}
}
| [
-1
] |
b9659c06532c1ab4a52f1665ec57267b33ad37c1 | f0c598e8737b7a441201cf4d78939143dfda1a73 | /MTChat/Classes/Extension/UIViewMTExtension.swift | 2433718c105175a24aaa5e54f65e75555552f0db | [] | no_license | zhixingxi/MTChat | 673c39366576cee48154a69df77d5ea0b6453db4 | cb9c371d1ea60b2f97614b011112ff0ae4540e51 | refs/heads/master | 2020-04-08T07:09:05.444702 | 2018-11-28T07:17:44 | 2018-11-28T07:17:44 | 159,128,851 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,440 | swift | //
// UIViewExtension.swift
// MTChat
//
// Created by IT A on 2018/11/26.
// Copyright © 2018 IT A. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
/**
依照图片轮廓对控制进行裁剪
- parameter stretchImage: 模子图片
- parameter stretchInsets: 模子图片的拉伸区域
*/
func clipShape(stretchImage: UIImage, stretchInsets: UIEdgeInsets) {
// 绘制 imageView 的 bubble layer
let bubbleMaskImage = stretchImage.resizableImage(withCapInsets: stretchInsets, resizingMode: .stretch)
// 设置图片的mask layer
let layer = CALayer()
layer.contents = bubbleMaskImage.cgImage
layer.contentsCenter = self.CGRectCenterRectForResizableImage(bubbleMaskImage)
layer.frame = self.bounds
layer.contentsScale = UIScreen.main.scale
layer.opacity = 1
self.layer.mask = layer
self.layer.masksToBounds = true
}
func CGRectCenterRectForResizableImage(_ image: UIImage) -> CGRect {
return CGRect(
x: image.capInsets.left / image.size.width,
y: image.capInsets.top / image.size.height,
width: (image.size.width - image.capInsets.right - image.capInsets.left) / image.size.width,
height: (image.size.height - image.capInsets.bottom - image.capInsets.top) / image.size.height
)
}
/// 裁剪 view 的圆角
func clipRectCorner(direction: UIRectCorner, cornerRadius: CGFloat) {
let cornerSize = CGSize(width: cornerRadius, height: cornerRadius)
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
}
/// 将View画成图
func trans2Image() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
let ctx = UIGraphicsGetCurrentContext()
self.layer.render(in: ctx!)
let newImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImg
}
public var x: CGFloat{
get{
return self.frame.origin.x
}
set{
var r = self.frame
r.origin.x = newValue
self.frame = r
}
}
public var y: CGFloat{
get{
return self.frame.origin.y
}
set{
var r = self.frame
r.origin.y = newValue
self.frame = r
}
}
/// 右边界的x值
public var rightX: CGFloat{
get{
return self.x + self.width
}
set{
var r = self.frame
r.origin.x = newValue - frame.size.width
self.frame = r
}
}
/// 下边界的y值
public var bottomY: CGFloat{
get{
return self.y + self.height
}
set{
var r = self.frame
r.origin.y = newValue - frame.size.height
self.frame = r
}
}
public var centerX : CGFloat{
get{
return self.center.x
}
set{
self.center = CGPoint(x: newValue, y: self.center.y)
}
}
public var centerY : CGFloat{
get{
return self.center.y
}
set{
self.center = CGPoint(x: self.center.x, y: newValue)
}
}
public var width: CGFloat{
get{
return self.frame.size.width
}
set{
var r = self.frame
r.size.width = newValue
self.frame = r
}
}
public var height: CGFloat{
get{
return self.frame.size.height
}
set{
var r = self.frame
r.size.height = newValue
self.frame = r
}
}
public var origin: CGPoint{
get{
return self.frame.origin
}
set{
self.x = newValue.x
self.y = newValue.y
}
}
public var size: CGSize{
get{
return self.frame.size
}
set{
self.width = newValue.width
self.height = newValue.height
}
}
}
| [
-1
] |
11eb920d9591aa9a6c4b3c6851fe3bfb07c5c3b6 | dcff4df0b15d043ecb072d3f560fe57a00ff8216 | /Kanchan Mittal Ministries/CollectionViewCells/KanchanCollectionView/KanchanCollectionViewCell.swift | 615ba900c005e6e9456c7cc9820621b22928278f | [] | no_license | cnfuzedRk62/Kanchan-Mittal | 6a5bc9028cce7126a17b21b8b51aaedf98c582b8 | c081aed922771521a839e383779d74c5bddf445e | refs/heads/master | 2020-09-27T00:15:40.057169 | 2019-12-06T17:19:00 | 2019-12-06T17:19:00 | 226,374,349 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 827 | swift | //
// KanchanCollectionViewCell.swift
// Kanchan Mittal Ministries
//
// Created by Ravinder on 25/11/19.
// Copyright © 2019 Ravinder. All rights reserved.
//
import UIKit
class KanchanCollectionViewCell: UICollectionViewCell {
@IBOutlet var sideImgView: UIImageView!
@IBOutlet var titleLBl: UILabel!
@IBOutlet var descriptionLbl: UILabel!
@IBOutlet var expolreMoreBtn: UIButton!
@IBOutlet var outerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
outerView.layer.cornerRadius = 10
outerView.layer.borderWidth = 1.0
outerView.layer.borderColor = UIColor.lightGray.cgColor
outerView.clipsToBounds = true
expolreMoreBtn.layer.cornerRadius = 5
expolreMoreBtn.clipsToBounds = true
}
}
| [
176338,
372603,
293965
] |
68f11adb9e2daf622dc7809e9a442abc82c8efb9 | cffba3d1d5f9ee9f1268a0296857e93528403371 | /GPS-MapKit-Swift-IB/ViewController.swift | 80fdf4b3b1095b95b7c6d095d4bcbe325ddcd204 | [] | no_license | CooperCodeComposer/GPS-MapKit-Swift-IB | 3ba938274895e7ae906de6a81eed4f8c52d8aaef | c6ff1b2624e8e55f7054a4f21cdca355788d0f69 | refs/heads/master | 2020-04-03T01:29:55.125698 | 2016-11-18T20:20:36 | 2016-11-18T20:20:36 | 60,599,965 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,739 | swift | //
// ViewController.swift
// GPS-MapKit-Swift-IB
//
// Created by Alistair Cooper on 5/30/16.
// Copyright © 2016 Alistair Cooper. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var headingLabel: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// build the json file
/*
let jsonObject = JsonBuilder.makeRestaurantArray()
let jsonString = JsonBuilder.JSONStringify(jsonObject: jsonObject, prettyPrinted: true)
print(jsonString)
*/
// setup core location
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let current: CLLocation = locations.last else { return }
let lat = current.coordinate.latitude
let lon = current.coordinate.longitude
latitudeLabel.text = String(format: "Latitude: %.6f", lat)
longitudeLabel.text = String(format: "Longitude: %.6f", lon)
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
headingLabel.text = String(format: "Heading: %.1f", newHeading.magneticHeading)
}
}
| [
-1
] |
b7a32d96919727cb9666629e59b8215aa693abe7 | 00c8949bf94a7410b2fed38aab671aae3afac20d | /CoachyFitApp/controllers/user/CoachesTableViewController.swift | 48285d42a1fdcb6a09164e50db3258406720832b | [] | no_license | ShonOhana/CoachyApp | 6ca6c2a6a38739e778bd215f62cc72e4d753ac8d | 59130f18a84e0d33e1b98a5e5b9fe786ff1bb548 | refs/heads/master | 2022-11-06T14:55:29.286654 | 2020-06-26T11:17:08 | 2020-06-26T11:17:08 | 275,128,134 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,360 | swift | //
// CoachesTableViewController.swift
// CoachyFitApp
//
// Created by Mac on 14/05/2020.
// Copyright © 2020 Mac. All rights reserved.
//
import UIKit
import SDWebImage
import PKHUD
import AVKit
class CoachesTableViewController: UITableViewController {
@IBOutlet weak var navTitle: UINavigationItem!
var coaches = [Coach]()
var kinds = ["TRX","CrossFit","פונקציונלי","בטן","אירובי","יוגה","פילאטיס","גומיות","אחר"]
var clickedPath: IndexPath? = nil
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
navigationItem.leftItemsSupplementBackButton = true
}
// 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 coaches.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "videoCell", for: indexPath) as? CoachTableViewCell
// Configure the cell...
let row = indexPath.row
cell?.separatorInset = UIEdgeInsets.zero;
cell?.delegate = self
cell?.videoDelegate = self
guard let title = title else {
return cell!
}
if kinds.contains(title){
cell?.populate(with: self.coaches[row], indexPath: indexPath, title: title)
}else{
cell?.populateForSearch(with: coaches, indexPath: indexPath, name: title)
}
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = clickedPath{
guard let dest = segue.destination as? CoachForClientViewController
else{
return
}
dest.coach = coaches[indexPath.row]
dest.videosArray = dest.coach.getFirstVideos(coach: dest.coach)
}
}
}
extension CoachesTableViewController: myTableDelegate{
func coachPageDelegate(_ cell: UITableViewCell) {
if let indexPath = self.tableView.indexPath(for: cell){
clickedPath = indexPath
performSegue(withIdentifier: "toCoachPage", sender: Any.self)
}
}
func videoDelegate(_ cell: UITableViewCell) {
if let indexPath = self.tableView.indexPath(for: cell){
clickedPath = indexPath
let videoString = coaches[clickedPath!.row].video[0]["uri"]
let videoUrl = URL(string: videoString as! String)
let player = AVPlayer(url: videoUrl!)
let vcPlayer = AVPlayerViewController()
vcPlayer.player = player
self.present(vcPlayer, animated: true, completion: nil)
}
}
}
| [
-1
] |
f0217a5cfeca5ef3a1cdc37d29e6ea90c407cd08 | 8b1e14a7d9201dd9e13b8b37c31fad4e69e50fc8 | /Code/ViewController/AboutMeWWDCViewController.swift | 9aaec3f2e9a91dfa90d9a012bca036b6b89d437e | [] | no_license | mohsinalimat/PortfolioApp | 865a010488e14e3f06b58f33d515c27125bb7caa | 23f22bfe9ed8bac5ac7ad218ec9982f8dc7e35ec | refs/heads/master | 2021-05-30T02:25:01.058873 | 2015-05-09T00:52:49 | 2015-05-09T00:52:49 | 111,390,170 | 1 | 0 | null | 2017-11-20T09:38:39 | 2017-11-20T09:38:39 | null | UTF-8 | Swift | false | false | 1,487 | swift | //
// AboutMeWWDCViewController.swift
// Portfolio
//
// Created by Eddie Kaiger on 4/19/15.
// Copyright (c) 2015 EddieKaiger. All rights reserved.
//
import UIKit
class AboutMeWWDCViewController: BaseChildViewController {
@IBOutlet weak private var headerLabel: UILabel!
@IBOutlet weak private var wwdcLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
configureHeaderLabel()
configureWWDCLabel()
}
// MARK: - Configure
private func configureHeaderLabel() {
self.headerLabel.text = "Oh, and I've always\nonly dreamed of attending"
self.headerLabel.textAlignment = .Center
self.headerLabel.textColor = self.defaultTextColor
self.headerLabel.numberOfLines = 0
self.headerLabel.font = UIFont.font(EKFontType.LightItalic, fontSize: 18)
}
private func configureWWDCLabel() {
self.wwdcLabel.text = "WWDC"
self.wwdcLabel.textColor = self.defaultTextColor
self.wwdcLabel.textAlignment = .Center
self.wwdcLabel.font = UIFont.font(EKFontType.Light, fontSize: 60)
}
// MARK: - EKScrollingDelegate
override func onScrollWithPageOnRight(offset: CGFloat) {
var vertTranslate: CGFloat = 300
self.headerLabel.transform = CGAffineTransformMakeTranslation(0, -offset * vertTranslate)
self.wwdcLabel.transform = CGAffineTransformMakeTranslation(0, offset * vertTranslate)
}
}
| [
-1
] |
353f18ed28ddf6ef36eacbf185da3e778c90a7d2 | 61bfb5bfe194c52bfeed65c09056d0706279a8a0 | /DriveKitCommonUI/Component/LastTripsWidget/View/LastTripsView.swift | 6294fbce82ee5ec5d1d5c56b39f239c3d73c3182 | [
"Apache-2.0"
] | permissive | DriveQuantPublic/drivekit-ui-ios | 9ed981e60a56836995633f2774af71baecaba46e | 565e08a191b1fc3f0173d77e402b605df20b7d73 | refs/heads/master | 2023-09-01T21:12:49.002287 | 2023-08-07T14:31:51 | 2023-08-07T14:31:51 | 216,339,601 | 3 | 2 | Apache-2.0 | 2023-09-14T15:13:14 | 2019-10-20T09:50:18 | Swift | UTF-8 | Swift | false | false | 5,760 | swift | // swiftlint:disable all
//
// LastTripsView.swift
// DriveKitCommonUI
//
// Created by David Bauduin on 19/08/2021.
// Copyright © 2021 DriveQuant. All rights reserved.
//
import UIKit
final class LastTripsView: UIView, Nibable {
@IBOutlet private weak var collectionView: UICollectionView!
@IBOutlet private weak var pageControl: UIPageControl!
private let sections: [LastTripsViewSection] = [.trips, .showAllTrips]
var viewModel: LastTripsViewModel? {
didSet {
update()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setupCollectionView()
setupPageControl()
}
private func setupCollectionView() {
self.collectionView.register(LastTripsViewCell.nib, forCellWithReuseIdentifier: "LastTripsViewCell")
self.collectionView.register(MoreTripsViewCell.nib, forCellWithReuseIdentifier: "MoreTripsViewCell")
}
private func setupPageControl() {
self.pageControl.pageIndicatorTintColor = DKUIColors.neutralColor.color
self.pageControl.currentPageIndicatorTintColor = DKUIColors.secondaryColor.color
}
private func update() {
if self.collectionView != nil {
self.collectionView.reloadData()
var numberOfItems = 0
for section in self.sections {
switch section {
case .trips:
numberOfItems += self.viewModel?.trips.count ?? 0
case .showAllTrips:
numberOfItems += 1
}
}
self.pageControl.numberOfPages = numberOfItems
}
}
}
extension LastTripsView: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.sections.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch self.sections[section] {
case .trips:
return self.viewModel?.trips.count ?? 0
case .showAllTrips:
return 1
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let viewModel = self.viewModel {
let cell: UICollectionViewCell
switch self.sections[indexPath.section] {
case .trips:
if let tripCell = collectionView.dequeueReusableCell(withReuseIdentifier: "LastTripsViewCell", for: indexPath) as? LastTripsViewCell {
let trip = viewModel.trips[indexPath.row]
tripCell.configure(trip: trip, tripData: viewModel.tripData, title: viewModel.titleForTrip(trip))
if let tripInfoView = tripCell.tripInfoView {
let gestureRec = UITapGestureRecognizer(target: self, action: #selector(tripInfoAction(_:)))
gestureRec.delegate = self
tripInfoView.addGestureRecognizer(gestureRec)
}
cell = tripCell
} else {
cell = UICollectionViewCell()
}
case .showAllTrips:
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MoreTripsViewCell", for: indexPath) as? MoreTripsViewCell ?? UICollectionViewCell()
}
return cell
} else {
return UICollectionViewCell()
}
}
@objc private func tripInfoAction(_ sender: UITapGestureRecognizer) {
if let tripInfoView = sender.view as? TripInfoView, let tripItem = tripInfoView.trip, let viewModel = self.viewModel {
viewModel.didSelectInfoView(of: tripItem)
}
}
}
extension LastTripsView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if let _ = touch.view as? TripInfoView { return true }
return false
}
}
extension LastTripsView: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let viewModel = self.viewModel {
switch self.sections[indexPath.section] {
case .trips:
viewModel.didSelectTrip(at: indexPath.row)
case .showAllTrips:
viewModel.didSelectAllTrips()
}
}
}
}
extension LastTripsView: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let index = scrollView.contentOffset.x / scrollView.bounds.width
self.pageControl.currentPage = Int(index)
}
}
extension LastTripsView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.bounds.size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
private enum LastTripsViewSection: Int {
case trips
case showAllTrips
}
| [
-1
] |
59365b9e67e493e0d54eddfd3ff89c27b64b54d5 | 147d01204c6ff4482fea10414d8ef22134244c84 | /Tests/RxCocoaTests/SentMessageTest.swift | 32d4f6482b41a895d5248f1b5e03825dfe96d988 | [
"MIT"
] | permissive | StYaphet/RxSwift | 2ce037c7bc58200162d0e32cd47c00ea61fad6c6 | 566d640b1dfb562ecc06112ce8ad9372e56d385c | refs/heads/master | 2021-01-13T04:31:05.894246 | 2017-01-23T10:16:48 | 2017-01-23T10:16:48 | 79,723,673 | 0 | 0 | null | 2017-01-22T14:48:35 | 2017-01-22T14:48:35 | null | UTF-8 | Swift | false | false | 62,654 | swift | //
// SentMessageTest.swift
// Tests
//
// Created by Krunoslav Zaher on 11/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import XCTest
import RxSwift
import RxCocoa
import RxBlocking
final class SentMessageTest : RxTest {
var testClosure: () -> () = { }
func dynamicClassName(_ baseClassName: String) -> String {
return "_RX_namespace_" + baseClassName
}
}
// MARK: Observing dealloc
extension SentMessageTest {
func testDealloc_baseClass_subClass_dont_interact1() {
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTestBase_dealloc) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTest_dealloc) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
}
func testDealloc_baseClass_subClass_dont_interact1_invokedMessage() {
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTestBase_dealloc) in
return [.methodInvoked(target.rx.methodInvoked(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
],
objectRealClassChange: [
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 0, methodsSwizzled: 0),
useIt: { _ in return [[[]]]})
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTest_dealloc) in
return [.methodInvoked(target.rx.methodInvoked(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
],
objectRealClassChange: [
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 0, methodsSwizzled: 0),
useIt: { _ in return [[[]]]})
}
func testDealloc_baseClass_subClass_dont_interact2() {
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTestBase_dealloc2) in
return [.sentMessage(target.rx.deallocating.map { _ in [] })]
},
objectActingClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTest_dealloc2) in
return [.sentMessage(target.rx.deallocating.map { _ in [] })]
},
objectActingClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
}
func testDealloc_baseClass_subClass_dont_interact_base_implements() {
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTestBase_dealloc_base) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTest_dealloc_base) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
}
func testDealloc_baseClass_subClass_dont_interact_base_implements_invokedMessage() {
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTestBase_dealloc_base) in
return [.methodInvoked(target.rx.methodInvoked(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
],
objectRealClassChange: [
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 0, methodsSwizzled: 0),
useIt: { _ in return [[[]]]})
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTest_dealloc_base) in
return [.methodInvoked(target.rx.methodInvoked(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
],
objectRealClassChange: [
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 0, methodsSwizzled: 0),
useIt: { _ in return [[[]]]})
}
func testDealloc_baseClass_subClass_dont_interact_subclass_implements() {
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTestBase_dealloc_subclass) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationAdded(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTest_dealloc_subclass) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
}
func testDealloc_baseClass_subClass_dont_interact_base_subclass_implements() {
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTestBase_dealloc_base_subclass) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
// swizzle normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: SentMessageTest_dealloc_base_subclass) in
return [.sentMessage(target.rx.sentMessage(NSSelectorFromString("dealloc")))]
},
objectActingClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
objectRealClassChange: [
.implementationChanged(forSelector: NSSelectorFromString("dealloc")),
],
runtimeChange: RxObjCRuntimeChange.changes(interceptedClasses: 1, methodsSwizzled: 1),
useIt: { _ in return [[[]]]})
}
}
// MARK: Observing by forwarding
extension SentMessageTest {
func testBaseClass_subClass_dont_interact_for_forwarding() {
// first forwarding with normal first
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(SentMessageTest_interact_forwarding.self),
observeIt: { target in
return [
ObservedSequence.sentMessage(target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledObject(toSay:)))),
ObservedSequence.methodInvoked(target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledObject(toSay:))))
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("SentMessageTest_interact_forwarding", andImplementsTheseSelectors: [
NSSelectorFromString("class"),
NSSelectorFromString("respondsToSelector:"),
NSSelectorFromString("methodSignatureForSelector:"),
NSSelectorFromString("forwardInvocation:"),
#selector(SentMessageTestBase_shared.justCalledObject(toSay:)),
NSSelectorFromString("_RX_namespace_justCalledObjectToSay:"),
])
],
runtimeChange: RxObjCRuntimeChange.changes(dynamicSubclasses:1, swizzledForwardClasses: 1, methodsForwarded: 1)
) { target in
let o = NSObject()
target.justCalledObject(toSay: o)
return [
[[o]],
[[o]]
]
}
// then forwarding base class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(SentMessageTestBase_interact_forwarding.self),
observeIt: { target in
return [
ObservedSequence.sentMessage(target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledObject(toSay:)))),
ObservedSequence.methodInvoked(target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledObject(toSay:))))
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("SentMessageTestBase_interact_forwarding", andImplementsTheseSelectors: [
NSSelectorFromString("class"),
NSSelectorFromString("respondsToSelector:"),
NSSelectorFromString("methodSignatureForSelector:"),
NSSelectorFromString("forwardInvocation:"),
#selector(SentMessageTestBase_shared.justCalledObject(toSay:)),
NSSelectorFromString("_RX_namespace_justCalledObjectToSay:"),
])
],
runtimeChange: RxObjCRuntimeChange.changes(dynamicSubclasses:1, swizzledForwardClasses: 1, methodsForwarded: 1)
) { target in
let o = NSObject()
target.justCalledObject(toSay: o)
return [
[[o]],
[[o]]
]
}
// then normal again, no changes
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(SentMessageTest_interact_forwarding.self),
observeIt: { target in
return [
ObservedSequence.sentMessage(target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledObject(toSay:)))),
ObservedSequence.methodInvoked(target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledObject(toSay:))))
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("SentMessageTest_interact_forwarding", andImplementsTheseSelectors: [
NSSelectorFromString("class"),
NSSelectorFromString("respondsToSelector:"),
NSSelectorFromString("methodSignatureForSelector:"),
NSSelectorFromString("forwardInvocation:"),
#selector(SentMessageTestBase_shared.justCalledObject(toSay:)),
NSSelectorFromString("_RX_namespace_justCalledObjectToSay:"),
])
],
runtimeChange: RxObjCRuntimeChange.changes()
) { target in
let o = NSObject()
target.justCalledObject(toSay: o)
return [
[[o]],
[[o]]
]
}
// then dynamic again, no changes
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(SentMessageTestBase_interact_forwarding.self),
observeIt: { target in
return [
ObservedSequence.sentMessage(target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledObject(toSay:)))),
ObservedSequence.methodInvoked(target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledObject(toSay:))))
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("SentMessageTestBase_interact_forwarding", andImplementsTheseSelectors: [
NSSelectorFromString("class"),
NSSelectorFromString("respondsToSelector:"),
NSSelectorFromString("methodSignatureForSelector:"),
NSSelectorFromString("forwardInvocation:"),
#selector(SentMessageTestBase_shared.justCalledObject(toSay:)),
NSSelectorFromString("_RX_namespace_justCalledObjectToSay:"),
])
],
runtimeChange: RxObjCRuntimeChange.changes()
) { target in
let o = NSObject()
target.justCalledObject(toSay: o)
return [
[[o]],
[[o]]
]
}
}
}
// MARK: Optimized observers don't interfere between class/baseclass
extension SentMessageTest {
func testBaseClass_subClass_dont_interact_for_optimized_version_void() {
_baseClass_subClass_dont_interact_for_optimized_version(
SentMessageTestBase_optimized_void.self,
SentMessageTest_optimized_void.self,
#selector(SentMessageTestBase_shared.voidJustCalledVoidToSay)) { target in
target.voidJustCalledVoidToSay()
return [
[[]],
[[]]
]
}
}
func testBaseClass_subClass_dont_interact_for_optimized_version_id() {
_baseClass_subClass_dont_interact_for_optimized_version(
SentMessageTestBase_optimized_id.self,
SentMessageTest_optimized_id.self,
#selector(SentMessageTestBase_shared.voidJustCalledObject(toSay:))) { target in
let o = NSObject()
target.voidJustCalledObject(toSay: o)
return [
[[o]],
[[o]]
]
}
}
func testBaseClass_subClass_dont_interact_for_optimized_version_int() {
_baseClass_subClass_dont_interact_for_optimized_version(
SentMessageTestBase_optimized_int.self,
SentMessageTest_optimized_int.self,
#selector(SentMessageTestBase_shared.voidJustCalledInt(toSay:))) { target in
target.voidJustCalledInt(toSay: 3)
return [
[[NSNumber(value: 3)]],
[[NSNumber(value: 3)]]
]
}
}
func testBaseClass_subClass_dont_interact_for_optimized_version_long() {
_baseClass_subClass_dont_interact_for_optimized_version(
SentMessageTestBase_optimized_long.self,
SentMessageTest_optimized_long.self,
#selector(SentMessageTestBase_shared.voidJustCalledLong(toSay:))) { target in
target.voidJustCalledLong(toSay: 3)
return [
[[NSNumber(value: 3)]],
[[NSNumber(value: 3)]]
]
}
}
func testBaseClass_subClass_dont_interact_for_optimized_version_char() {
_baseClass_subClass_dont_interact_for_optimized_version(
SentMessageTestBase_optimized_char.self,
SentMessageTest_optimized_char.self,
#selector(SentMessageTestBase_shared.voidJustCalledChar(toSay:))) { target in
target.voidJustCalledChar(toSay: 3)
return [
[[NSNumber(value: 3)]],
[[NSNumber(value: 3)]]
]
}
}
func testBaseClass_subClass_dont_interact_for_optimized_version_id_id() {
_baseClass_subClass_dont_interact_for_optimized_version(
SentMessageTestBase_optimized_id_id.self,
SentMessageTest_optimized_id_id.self,
#selector(SentMessageTestBase_shared.voidJustCalledObject(toSay:object:))) { target in
let o = NSObject()
let o1 = NSObject()
target.voidJustCalledObject(toSay: o, object: o1)
return [
[[o, o1]],
[[o, o1]]
]
}
}
func _baseClass_subClass_dont_interact_for_optimized_version
<
BaseClass: SentMessageTestClassCreationProtocol & NSObjectProtocol,
TargetClass: SentMessageTestClassCreationProtocol & NSObjectProtocol
>(_ baseClass: BaseClass.Type, _ targetClass: TargetClass.Type, _ method: Selector, _ invoke: @escaping (BaseClass) -> [[MethodParameters]]) {
// now force forwarding mechanism for normal class
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { target in
return [
.sentMessage((target as! NSObject).rx.sentMessage(method)),
.methodInvoked((target as! NSObject).rx.methodInvoked(method)),
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("\(targetClass)", andImplementsTheseSelectors: [method, NSSelectorFromString("class")])
],
runtimeChange: RxObjCRuntimeChange.changes(dynamicSubclasses: 1, methodsSwizzled: 1)) { (target: TargetClass) in
return invoke(target as! BaseClass)
}
// first force base class forwarding
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: BaseClass) in
return [
.sentMessage((target as! NSObject).rx.sentMessage(method)),
.methodInvoked((target as! NSObject).rx.methodInvoked(method)),
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("\(baseClass)", andImplementsTheseSelectors: [method, NSSelectorFromString("class")])
],
runtimeChange: RxObjCRuntimeChange.changes(dynamicSubclasses: 1, methodsSwizzled: 1),
useIt: invoke)
// now force forwarding mechanism for normal class again
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { target in
return [
.sentMessage((target as! NSObject).rx.sentMessage(method)),
.methodInvoked((target as! NSObject).rx.methodInvoked(method)),
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("\(targetClass)", andImplementsTheseSelectors: [method, NSSelectorFromString("class")])
],
runtimeChange: RxObjCRuntimeChange.changes()) { (target: TargetClass) in
return invoke(target as! BaseClass)
}
// forwarding for base class again
ensureGlobalRuntimeChangesAreCached(
createNormalInstance(),
observeIt: { (target: BaseClass) in
return [
.sentMessage((target as! NSObject).rx.sentMessage(method)),
.methodInvoked((target as! NSObject).rx.methodInvoked(method)),
]
},
objectActingClassChange: [
],
objectRealClassChange: [
ObjectRuntimeChange.ClassChangedToDynamic("\(baseClass)", andImplementsTheseSelectors: [method, NSSelectorFromString("class")])
],
runtimeChange: RxObjCRuntimeChange.changes(),
useIt: invoke)
}
}
// MARK: Optimized observers don't interfere between class/baseclass depending on who is implementing the method
extension SentMessageTest {
func testBaseClass_subClass_dont_interact_for_optimized_version_int_base_implements() {
let argument = NSObject()
_baseClass_subClass_dont_interact_for_optimized_version(
SentMessageTestBase_optimized_int_base.self,
SentMessageTest_optimized_int_base.self,
#selector(SentMessageTestBase_optimized_int_base.optimized(_:))) { target in
target.optimized(argument)
return [
[[argument]],
[[argument]]
]
}
}
}
// MARK: Basic observing by forwarding cases
extension SentMessageTest {
func testBasicForwardingCase() {
let target = SentMessageTest_forwarding_basic()
var messages = [[Any]]()
var messageStage: [MessageProcessingStage] = []
let d = target.rx.sentMessage(#selector(SentMessageTestBase_shared.message_allSupportedParameters(_:p2:p3:p4:p5:p6:p7:p8:p9:p10:p11:p12:p13:p14:p15:p16:))).subscribe(onNext: { n in
messages.append(n)
messageStage.append(.sentMessage)
}, onError: { e in
XCTFail("Errors out \(e)")
})
let d2 = target.rx.methodInvoked(#selector(SentMessageTestBase_shared.message_allSupportedParameters(_:p2:p3:p4:p5:p6:p7:p8:p9:p10:p11:p12:p13:p14:p15:p16:))).subscribe(onNext: { n in
messages.append(n)
messageStage.append(.methodInvoked)
}, onError: { e in
XCTFail("Errors out \(e)")
})
let objectParam = NSObject()
let str: UnsafePointer<Int8> = UnsafePointer(bitPattern: 1343423)!
let unsafeStr: UnsafeMutablePointer<Int8> = UnsafeMutablePointer(bitPattern: 2123123)!
let largeStruct = some_insanely_large_struct(a: (0, 1, 2, 3, 4, 5, 6, 7), some_large_text: nil, next: nil)
target.invokedMethod = {
messageStage.append(.invoking)
}
target.message_allSupportedParameters(objectParam, p2: type(of: target), p3: { x in x}, p4: -2, p5: -3, p6: -4, p7: -5,
p8: 1, p9: 2, p10: 3, p11: 4, p12: 1.0, p13: 2.0, p14: str, p15: unsafeStr, p16: largeStruct)
d.dispose()
d2.dispose()
let resultMessages = target.messages.map { $0.values }
XCTAssertEqualAnyObjectArrayOfArrays(resultMessages + resultMessages, messages)
XCTAssertEqual(messageStage, [.sentMessage, .invoking, .methodInvoked])
}
}
// MARK: Test failures
extension SentMessageTest {
func testFailsInCaseObservingUnknownSelector_sentMessage() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.sentMessage(NSSelectorFromString("unknownSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .selectorNotImplemented(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testFailsInCaseObservingUnknownSelector_methodInvoked() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.methodInvoked(NSSelectorFromString("unknownSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .selectorNotImplemented(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testFailsInCaseObjectIsAlreadyBeingInterceptedWithKVO_sentMessage() {
let target = SentMessageTest_shared()
let disposeBag = DisposeBag()
target.rx.observe(NSArray.self, "messages")
.subscribe(onNext: { _ in
})
.addDisposableTo(disposeBag)
do {
_ = try target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .objectMessagesAlreadyBeingIntercepted(let targetInError, let mechanism) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
XCTAssertEqual(mechanism, RxCocoaInterceptionMechanism.kvo)
}
}
func testFailsInCaseObjectIsAlreadyBeingInterceptedWithKVO_methodInvoked() {
let target = SentMessageTest_shared()
let disposeBag = DisposeBag()
target.rx.observe(NSArray.self, "messages")
.subscribe(onNext: { _ in
})
.addDisposableTo(disposeBag)
do {
_ = try target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .objectMessagesAlreadyBeingIntercepted(let targetInError, let mechanism) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
XCTAssertEqual(mechanism, RxCocoaInterceptionMechanism.kvo)
}
}
func testFailsInCaseObjectIsAlreadyBeingInterceptedWithSomeOtherMechanism_sentMessage() {
let target = SentMessageTest_shared()
object_setClass(target, SentMessageTest_shared_mock_interceptor.self)
do {
_ = try target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .objectMessagesAlreadyBeingIntercepted(let targetInError, let mechanism) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
XCTAssertEqual(mechanism, RxCocoaInterceptionMechanism.kvo)
}
}
func testFailsInCaseObjectIsAlreadyBeingInterceptedWithSomeOtherMechanism_methodInvoked() {
let target = SentMessageTest_shared()
object_setClass(target, SentMessageTest_shared_mock_interceptor.self)
do {
_ = try target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .objectMessagesAlreadyBeingIntercepted(let targetInError, let mechanism) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
XCTAssertEqual(mechanism, RxCocoaInterceptionMechanism.kvo)
}
}
func testFailsInCaseObjectIsCF_sentMessage() {
autoreleasepool {
let target = "\(Date())"
do {
_ = try target.rx.sentMessage(#selector(getter: NSString.length))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .cantInterceptCoreFoundationTollFreeBridgedObjects(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual((targetInError as! NSString) as String, target)
}
}
}
func testFailsInCaseObjectIsCF_methodInvoked() {
autoreleasepool {
let target = "\(Date())"
do {
_ = try target.rx.sentMessage(#selector(getter: NSString.length))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .cantInterceptCoreFoundationTollFreeBridgedObjects(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual((targetInError as! NSString) as String, target)
}
}
}
}
// MARK: Test interaction with KVO
extension SentMessageTest {
func testWorksWithKVOInCaseKVORegisteredAfter_sentMessage() {
let target = SentMessageTest_shared()
let messages = target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
var stages: [MessageProcessingStage] = []
let kvo = target.rx.observe(NSArray.self, "messages")
.subscribe(onNext: { _ in
})
var recordedMessages = [MethodParameters]()
let methodObserving = messages.subscribe(onNext: { n in
stages.append(.sentMessage)
recordedMessages.append(n)
})
target.invokedMethod = {
stages.append(.invoking)
}
target.justCalledBool(toSay: true)
kvo.dispose()
target.justCalledBool(toSay: false)
XCTAssertEqual(stages, [.sentMessage, .invoking, .sentMessage, .invoking])
XCTAssertEqualAnyObjectArrayOfArrays(recordedMessages, [[NSNumber(value: true)], [NSNumber(value: false)]])
methodObserving.dispose()
}
func testWorksWithKVOInCaseKVORegisteredAfter_methodInvoked() {
let target = SentMessageTest_shared()
let messages = target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
var stages: [MessageProcessingStage] = []
let kvo = target.rx.observe(NSArray.self, "messages")
.subscribe(onNext: { _ in
})
var recordedMessages = [MethodParameters]()
let methodObserving = messages.subscribe(onNext: { n in
stages.append(.methodInvoked)
recordedMessages.append(n)
})
target.invokedMethod = {
stages.append(.invoking)
}
target.justCalledBool(toSay: true)
kvo.dispose()
target.justCalledBool(toSay: false)
XCTAssertEqual(stages, [.invoking, .methodInvoked, .invoking, .methodInvoked])
XCTAssertEqualAnyObjectArrayOfArrays(recordedMessages, [[NSNumber(value: true)], [NSNumber(value: false)]])
methodObserving.dispose()
}
}
// MARK: Test subjects
extension SentMessageTest {
func testMessageSentSubjectHasPublishBehavior() {
var messages: Observable<MethodParameters>!
var recordedMessages = [MethodParameters]()
var completed = false
let disposeBag = DisposeBag()
var stages: [MessageProcessingStage] = []
autoreleasepool {
let target = SentMessageTest_shared()
messages = target.rx.sentMessage(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
target.invokedMethod = {
stages.append(.invoking)
}
target.justCalledBool(toSay: true)
messages.subscribe(onNext: { n in
recordedMessages.append(n)
stages.append(.sentMessage)
}, onCompleted: {
completed = true
}).addDisposableTo(disposeBag)
target.justCalledBool(toSay: true)
}
XCTAssertEqual(stages, [.invoking, .sentMessage, .invoking])
XCTAssertEqualAnyObjectArrayOfArrays(recordedMessages, [[NSNumber(value: true)]])
XCTAssertTrue(completed)
}
func testInvokedMethodSubjectHasPublishBehavior() {
var messages: Observable<MethodParameters>!
var recordedMessages = [MethodParameters]()
var completed = false
let disposeBag = DisposeBag()
var stages: [MessageProcessingStage] = []
autoreleasepool {
let target = SentMessageTest_shared()
messages = target.rx.methodInvoked(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)))
target.invokedMethod = {
stages.append(.invoking)
}
target.justCalledBool(toSay: true)
messages.subscribe(onNext: { n in
recordedMessages.append(n)
stages.append(.methodInvoked)
}, onCompleted: {
completed = true
}).addDisposableTo(disposeBag)
target.justCalledBool(toSay: true)
}
XCTAssertEqual(stages, [.invoking, .invoking, .methodInvoked])
XCTAssertEqualAnyObjectArrayOfArrays(recordedMessages, [[NSNumber(value: true)]])
XCTAssertTrue(completed)
}
func testDeallocSubjectHasReplayBehavior1() {
var deallocSequence: Observable<MethodParameters>!
autoreleasepool {
let target = SentMessageTest_shared()
deallocSequence = target.rx.sentMessage(NSSelectorFromString("dealloc"))
}
var called = false
var completed = false
_ = deallocSequence.subscribe(onNext: { n in
called = true
}, onCompleted: {
completed = true
})
XCTAssertTrue(called)
XCTAssertTrue(completed)
}
func testDeallocSubjectHasReplayBehavior2() {
var deallocSequence: Observable<()>!
autoreleasepool {
let target = SentMessageTest_shared()
deallocSequence = target.rx.deallocating
}
var called = false
var completed = false
_ = deallocSequence.subscribe(onNext: { n in
called = true
}, onCompleted: {
completed = true
})
XCTAssertTrue(called)
XCTAssertTrue(completed)
}
}
// MARK: Test observing of special methods fail
extension SentMessageTest {
func testObserve_special_class_sentMessage() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.sentMessage(NSSelectorFromString("class"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_special_class_methodInvoked() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.methodInvoked(NSSelectorFromString("class"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_special_forwardingTargetForSelector_sentMessage() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.sentMessage(NSSelectorFromString("forwardingTargetForSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_special_forwardingTargetForSelector_methodInvoked() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.methodInvoked(NSSelectorFromString("forwardingTargetForSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_special_methodSignatureForSelector_sentMessage() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.sentMessage(NSSelectorFromString("methodSignatureForSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_special_methodSignatureForSelector_methodInvoked() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.methodInvoked(NSSelectorFromString("methodSignatureForSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_special_respondsToSelector_sentMessage() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.sentMessage(NSSelectorFromString("respondsToSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_special_respondsToSelector_methodInvoked() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.methodInvoked(NSSelectorFromString("respondsToSelector:"))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingPerformanceSensitiveMessages(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
}
// MARK: Test return value check
extension SentMessageTest {
func testObserve_largeStructReturnValueFails_sentMessage() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.sentMessage(#selector(SentMessageTestBase_shared.hugeResult))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingMessagesWithUnsupportedReturnType(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
func testObserve_largeStructReturnValueFails_methodInvoked() {
let target = SentMessageTest_shared()
do {
_ = try target.rx.methodInvoked(#selector(SentMessageTestBase_shared.hugeResult))
.toBlocking()
.first()
XCTFail()
}
catch let e {
guard case .observingMessagesWithUnsupportedReturnType(let targetInError) = e as! RxCocoaObjCRuntimeError else {
XCTFail()
return
}
XCTAssertEqual(targetInError as? SentMessageTest_shared, target)
}
}
}
// MARK: Ensure all types are covered
extension SentMessageTest {
func testObservingForAllTypes() {
let object = SentMessageTest_all_supported_types()
let closure: () -> () = { }
let constChar = ("you better be listening" as NSString).utf8String!
let largeStruct = some_insanely_large_struct(a: (0, 1, 2, 3, 4, 5, 6, 7), some_large_text: nil, next: nil)
let startRuntimeState = RxObjCRuntimeState()
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledObject(toSay:)),
sendMessage: { x in NSValue(nonretainedObject: x.justCalledObject(toSay: object)) },
expectedResult: NSValue(nonretainedObject: object))
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledClass(toSay:)), sendMessage: { x in NSValue(nonretainedObject: x.justCalledClass(toSay: type(of: object))) }, expectedResult: NSValue(nonretainedObject: type(of: object)))
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledClosure(toSay:)),
sendMessage: { x in "\(x.justCalledClosure(toSay: closure))" },
expectedResult: "\(closure)")
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledChar(toSay:)),
sendMessage: { x in x.justCalledChar(toSay: 3)},
expectedResult: 3)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledShort(toSay:)),
sendMessage: { x in x.justCalledShort(toSay: 4) },
expectedResult: 4)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledInt(toSay:)),
sendMessage: { x in x.justCalledInt(toSay: 5) },
expectedResult: 5)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledLong(toSay:)),
sendMessage: { x in x.justCalledLong(toSay: 6) },
expectedResult: 6)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledLongLong(toSay:)),
sendMessage: { x in x.justCalledLongLong(toSay: 7) },
expectedResult: 7)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledUnsignedChar(toSay:)),
sendMessage: { x in x.justCalledUnsignedChar(toSay: 8) },
expectedResult: 8)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledUnsignedShort(toSay:)),
sendMessage: { x in x.justCalledUnsignedShort(toSay: 9) },
expectedResult: 9)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledUnsignedInt(toSay:)),
sendMessage: { x in x.justCalledUnsignedInt(toSay: 10) },
expectedResult: 10)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledUnsignedLong(toSay:)),
sendMessage: { x in x.justCalledUnsignedLong(toSay: 11) },
expectedResult: 11)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledUnsignedLongLong(toSay:)),
sendMessage: { x in x.justCalledUnsignedLongLong(toSay: 12) },
expectedResult: 12)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledFloat(toSay:)),
sendMessage: { x in x.justCalledFloat(toSay: 13) },
expectedResult: 13)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledDouble(toSay:)),
sendMessage: { x in x.justCalledDouble(toSay: 13) },
expectedResult: 13)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledBool(toSay:)),
sendMessage: { x in x.justCalledBool(toSay: true) },
expectedResult: true)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledConstChar(toSay:)),
sendMessage: { x in x.justCalledConstChar(toSay: constChar) },
expectedResult: constChar)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.justCalledLarge(toSay:)),
sendMessage: { x in x.justCalledLarge(toSay: largeStruct) },
expectedResult: 28)
let middleRuntimeState = RxObjCRuntimeState()
let middleChanges = RxObjCRuntimeChange.changes(dynamicSubclasses: 1, swizzledForwardClasses: 1, methodsForwarded: 18)
middleRuntimeState.assertAfterThisMoment(startRuntimeState, changed:middleChanges)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledObject(toSay:)), sendMessage: { x in x.voidJustCalledObject(toSay: object); return NSValue(nonretainedObject: object) }, expectedResult: NSValue(nonretainedObject: object))
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledClosure(toSay:)),
sendMessage: { x in x.voidJustCalledClosure(toSay: closure); return "\(closure)" },
expectedResult: "\(closure)")
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledChar(toSay:)),
sendMessage: { x in x.voidJustCalledChar(toSay: 3); return 3 },
expectedResult: 3)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledShort(toSay:)),
sendMessage: { x in x.voidJustCalledShort(toSay: 4); return 4 },
expectedResult: 4)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledInt(toSay:)),
sendMessage: { x in x.voidJustCalledInt(toSay: 5); return 5 },
expectedResult: 5)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledLong(toSay:)),
sendMessage: { x in x.voidJustCalledLong(toSay: 6); return 6 },
expectedResult: 6)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledUnsignedChar(toSay:)),
sendMessage: { x in x.voidJustCalledUnsignedChar(toSay: 8); return 8 },
expectedResult: 8)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledUnsignedShort(toSay:)),
sendMessage: { x in x.voidJustCalledUnsignedShort(toSay: 9); return 9 },
expectedResult: 9)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledUnsignedInt(toSay:)),
sendMessage: { x in x.voidJustCalledUnsignedInt(toSay: 10); return 10 },
expectedResult: 10)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledUnsignedLong(toSay:)),
sendMessage: { x in x.voidJustCalledUnsignedLong(toSay: 11); return 11 },
expectedResult: 11)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledDouble(toSay:)),
sendMessage: { x in x.voidJustCalledDouble(toSay: 13); return 13 },
expectedResult: 13)
_testMessageRecordedAndAllCallsAreMade(#selector(SentMessageTestBase_shared.voidJustCalledFloat(toSay:)), sendMessage: { x in x.voidJustCalledFloat(toSay: 13); return 13 }, expectedResult: 13)
let endRuntimeState = RxObjCRuntimeState()
endRuntimeState.assertAfterThisMoment(middleRuntimeState, changed: RxObjCRuntimeChange.changes(methodsSwizzled: 12))
}
func _testMessageRecordedAndAllCallsAreMade<Result: Equatable>(_ selector: Selector, sendMessage: @escaping (SentMessageTest_all_supported_types) -> Result, expectedResult: Result) {
_testMessageRecordedAndAllCallsAreMade(selector, sendMessage: sendMessage, expectedResult: expectedResult) { target, selector in
return ObservedSequence.sentMessage(target.rx.sentMessage(selector))
}
_testMessageRecordedAndAllCallsAreMade(selector, sendMessage: sendMessage, expectedResult: expectedResult) { target, selector in
return ObservedSequence.methodInvoked(target.rx.methodInvoked(selector))
}
}
func _testMessageRecordedAndAllCallsAreMade<Result: Equatable>(_ selector: Selector, sendMessage: @escaping (SentMessageTest_all_supported_types) -> Result, expectedResult: Result, methodSelector: @escaping (SentMessageTest_all_supported_types, Selector) -> ObservedSequence) {
var observedMessages = [[Any]]()
var receivedDerivedClassMessage = [[Any]]()
var receivedBaseClassMessage = [[Any]]()
var completed = false
var result: Result! = nil
var stages: [MessageProcessingStage] = []
let action: () -> Disposable = { () -> Disposable in
let target = SentMessageTest_all_supported_types()
let observedSequence = methodSelector(target, selector)
let d = observedSequence.sequence.subscribe(onNext: { n in
stages.append(observedSequence.stage)
observedMessages.append(n)
}, onError: { e in
XCTFail("Errors out \(e)")
}, onCompleted: {
completed = true
})
target.invokedMethod = {
stages.append(.invoking)
}
result = sendMessage(target)
receivedDerivedClassMessage = target.messages.map { $0.values }
receivedBaseClassMessage = target.baseMessages.map { $0.values }
return d
}
action().dispose()
XCTAssertEqual(stages, stages.sorted(by: { $0.rawValue < $1.rawValue }))
XCTAssertTrue(stages.count > 0)
XCTAssertEqual(result, expectedResult)
XCTAssertTrue(completed)
XCTAssert(observedMessages.count == 1)
XCTAssertEqualAnyObjectArrayOfArrays(observedMessages, receivedDerivedClassMessage)
XCTAssertEqualAnyObjectArrayOfArrays(observedMessages, receivedBaseClassMessage)
}
}
extension SentMessageTest {
/**
Repeats action twice and makes sure there is no global leaks. Observing mechanism is lazy loaded so not caching
results properly can cause serious memory leaks.
*/
func ensureGlobalRuntimeChangesAreCached<T: SentMessageTestClassCreationProtocol & NSObjectProtocol>(
_ createIt: @escaping () -> T,
observeIt: @escaping (T) -> [ObservedSequence],
objectActingClassChange: [ObjectRuntimeChange],
objectRealClassChange: [ObjectRuntimeChange],
runtimeChange: RxObjCRuntimeChange,
useIt: @escaping (T) -> [[MethodParameters]]
) {
// First run normal experiment
_ensureGlobalRuntimeChangesAreCached(createIt,
observeIt: observeIt,
expectedActingClassChanges: objectActingClassChange,
expectedRealClassChanges: objectRealClassChange,
runtimeChange: runtimeChange,
useIt: useIt
)
// The second run of the same experiment shouldn't cause any changes in global runtime.
// Cached methods should be used.
// If second experiment causes some change in runtime, that means there is a bug.
_ensureGlobalRuntimeChangesAreCached(createIt,
observeIt: observeIt,
expectedActingClassChanges: [], // acting class can't change second time, because that would mean that on every observe attempt we would inject new methods in runtime
expectedRealClassChanges: objectRealClassChange.filter { $0.isClassChange }, // only class can change to the same class it changed originally
runtimeChange: RxObjCRuntimeChange.changes(),
useIt: useIt
)
}
func _ensureGlobalRuntimeChangesAreCached<T: SentMessageTestClassCreationProtocol & NSObjectProtocol> (
_ createIt: () -> T,
observeIt: (T) -> [ObservedSequence],
expectedActingClassChanges: [ObjectRuntimeChange],
expectedRealClassChanges: [ObjectRuntimeChange],
runtimeChange: RxObjCRuntimeChange,
useIt: (T) -> [[MethodParameters]]
) {
let originalRuntimeState = RxObjCRuntimeState()
var createdObject: T! = nil
var disposables = [Disposable]()
var nCompleted = 0
var recordedParameters = [[MethodParameters]]()
var observables: [ObservedSequence] = []
autoreleasepool {
createdObject = createIt()
let afterCreateState = RxObjCRuntimeState()
afterCreateState.assertAfterThisMoment(originalRuntimeState, changed: RxObjCRuntimeChange.changes())
}
let originalObjectRuntimeState = ObjectRuntimeState(target: createdObject)
autoreleasepool {
observables = observeIt(createdObject)
}
let afterObserveObjectRuntimeState = ObjectRuntimeState(target: createdObject)
let afterObserveRuntimeState = RxObjCRuntimeState()
afterObserveObjectRuntimeState.assertChangesFrom(originalObjectRuntimeState,
expectedActingClassChanges: expectedActingClassChanges,
expectedRealClassChanges: expectedRealClassChanges
)
afterObserveRuntimeState.assertAfterThisMoment(originalRuntimeState, changed: runtimeChange)
var messageProcessingStage: [MessageProcessingStage] = []
autoreleasepool {
var i = 0
for o in observables {
let index = i
i += 1
recordedParameters.append([])
_ = o.sequence.subscribe(onNext: { n in
messageProcessingStage.append(o.stage)
recordedParameters[index].append(n)
}, onError: { e in
XCTFail("Error happened \(e)")
}, onCompleted: { () -> Void in
nCompleted += 1
})
}
}
var invokedCount = 0
createdObject.invokedMethod = {
messageProcessingStage.append(.invoking)
invokedCount = invokedCount + 1
}
let expectedParameters = useIt(createdObject)
let finalObjectRuntimeState = ObjectRuntimeState(target: createdObject)
finalObjectRuntimeState.assertChangesFrom(afterObserveObjectRuntimeState,
expectedActingClassChanges: [],
expectedRealClassChanges: []
)
autoreleasepool {
for d in disposables {
d.dispose()
}
disposables = []
// tiny second test to make sure runtime stayed intact
createdObject = nil
}
// ensure all observables are completed on object dispose
XCTAssertTrue(nCompleted == observables.count)
// expected parameters should be sorted
XCTAssertEqual(messageProcessingStage, messageProcessingStage.sorted(by: { $0.rawValue < $1.rawValue }))
XCTAssertEqual(messageProcessingStage.count, observables.count + invokedCount)
XCTAssertEqual(recordedParameters.count, expectedParameters.count)
for (lhs, rhs) in zip(recordedParameters, expectedParameters) {
XCTAssertEqualAnyObjectArrayOfArrays(lhs, rhs)
}
// nothing is changed after requesting the observables
let endRuntimeState = RxObjCRuntimeState()
endRuntimeState.assertAfterThisMoment(afterObserveRuntimeState, changed: RxObjCRuntimeChange.changes())
}
}
// MARK: Convenience
extension SentMessageTest {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
}
func createKVODynamicSubclassed<T: SentMessageTestClassCreationProtocol & NSObjectProtocol>(_ type: T.Type = T.self) -> () -> (T, [Disposable]) {
return {
let t = T.createInstance()
//let disposable = (t as! NSObject).rx.observe(NSArray.self, "messages").publish().connect()
(t as! NSObject).addObserver(self, forKeyPath: "messages", options: [], context: nil)
return (t, [Disposables.create { (t as! NSObject).removeObserver(self, forKeyPath: "messages") }])
}
}
func createNormalInstance<T: SentMessageTestClassCreationProtocol & NSObjectProtocol>(_ type: T.Type = T.self) -> () -> T {
return {
return T.createInstance()
}
}
}
extension some_insanely_large_struct : Equatable {
}
public func ==(lhs: some_insanely_large_struct, rhs: some_insanely_large_struct) -> Bool {
if lhs.a.0 != rhs.a.0 { return false }
if lhs.a.1 != rhs.a.1 { return false }
if lhs.a.2 != rhs.a.2 { return false }
if lhs.a.3 != rhs.a.3 { return false }
if lhs.a.4 != rhs.a.4 { return false }
if lhs.a.5 != rhs.a.5 { return false }
if lhs.a.6 != rhs.a.6 { return false }
if lhs.a.7 != rhs.a.7 { return false }
return lhs.some_large_text == rhs.some_large_text && lhs.next == rhs.next
}
| [
170867,
298155,
286670
] |
3024004ef356e4ecb71c9f1c4b0c49a12ac05832 | 59fdfb47cf27fd96b19c218c2413af5f24e16a7f | /Rocket.Chat/AppDelegate.swift | a14bc92f1ba2c6a01defd32b01dfb5b6e90c61df | [
"MIT"
] | permissive | CodeBanBan/Rocket.Chat.iOS | 51f1bbc71c97839acad89e288627e4dcdce00d04 | 0e7f72e98887dcf125149e2cf0b4a94ed0162b53 | refs/heads/develop | 2020-04-01T17:39:23.690264 | 2016-10-29T17:09:02 | 2016-10-29T17:09:02 | 68,369,552 | 0 | 0 | null | 2016-09-16T09:58:00 | 2016-09-16T09:57:59 | null | UTF-8 | Swift | false | false | 512 | swift | //
// AppDelegate.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/5/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self])
return true
}
}
| [
309520,
354680,
382254
] |
880f903303bf9b32a3ffa42ffb8e055d79d7baf1 | 58ce4d884502f224f9aa161be84a87417238ea7f | /Radio-data/Modules/Network/Requests/SearchResponseModel.swift | 94652cf4b4ef4752b8a84275ec1e9fe264738125 | [
"MIT"
] | permissive | Daedren/radio-ios | 052cefc8dfc87a2fd9422cd165121ef1e6997c06 | 06fae6ebbdd3c78c974491f51a90cfd061c84991 | refs/heads/master | 2022-12-02T02:02:38.774029 | 2022-11-19T22:28:03 | 2022-11-19T22:28:03 | 221,068,028 | 2 | 0 | MIT | 2019-11-15T21:29:35 | 2019-11-11T20:52:25 | Swift | UTF-8 | Swift | false | false | 544 | swift | import Foundation
public struct SearchResponseModel: Decodable {
let total, perPage, currentPage, lastPage: Int
let from, to: Int
let data: [SearchedTrackResponseModel]
enum CodingKeys: String, CodingKey {
case total
case perPage = "per_page"
case currentPage = "current_page"
case lastPage = "last_page"
case from, to, data
}
}
struct SearchedTrackResponseModel: Decodable {
let artist, title: String
let id, lastplayed, lastrequested: Int
let requestable: Bool
}
| [
-1
] |
90e832d982009b67c5407eaafb3ebd137e3d267d | a403dcbcb2bed6695ebeacf0e295b1b9c1aea9d0 | /chap6Loops.playground/Contents.swift | ed16bdf58c669a26a62345c21856465d819408ae | [] | no_license | tuanvpham/learningSwift | ff847c9ee801e0d5ad5bf1c9494289cd91347cf2 | c9a1077ac27f94dc1b8dd208584929625beff64a | refs/heads/master | 2021-01-09T06:02:19.190576 | 2017-03-28T04:04:29 | 2017-03-28T04:04:29 | 80,896,909 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 693 | swift | //: Playground - noun: a place where people can play
import UIKit
// For-in Loop
var myFirstInt: Int = 0
for i in 1...5 {
myFirstInt += 1
print("my integer equals \(myFirstInt) at iteration \(i)")
}
// For-Case Loop
for case let i in 1...100 where i % 3 == 0{
print(i)
}
// For Loop (classic) - has been removed since Swift 3
/* for initialization; condition; increment {
code to execute
}
*/
// While Loop - best for number of iterations pass through is unknown
var i = 1
while i < 6 {
myFirstInt += 1
print(myFirstInt)
i += 1
}
//Repeat-While Loop - execute the code once before it checks the conditions
repeat {
print(myFirstInt)
i+=1
} while i < 6
| [
-1
] |
cf5db424538ef62826edc3f671ff44bb8d4cc73b | b016cf2aa4a072817224e4c47403ebf45cbfc842 | /Closures/MarkToGrade.swift | a8a9215993071d5743652a8496213d591f74a18a | [] | no_license | waihon/SwiftInSixtySeconds | 251facdb815d5b27ada4d5295d89ce5737752f68 | 6c4862f2eddd80dfda5d459fa05999df7c6d32b0 | refs/heads/main | 2023-05-03T02:28:22.713876 | 2021-05-17T12:34:23 | 2021-05-17T12:34:23 | 364,741,523 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 823 | swift | func markToGrade(mark: Int, gradeMapping: (Int) -> String) -> String {
print("Your mark was \(mark)%.")
let grade = gradeMapping(mark)
return "That's \'\(grade)\'."
}
let result = markToGrade(mark: 80) { (mark: Int) -> String in
// https://en.wikipedia.org/wiki/Grading_systems_by_country#Malaysia
let grade: String
switch mark {
case 91...100:
grade = "Exceptional"
case 81...90:
grade = "Excellent"
case 71...80:
grade = "Good"
case 61...70:
grade = "Fairly good"
case 51...60:
grade = "Satisfactory"
case 41...50:
grade = "Poor"
default:
grade = "Fail"
}
return grade
}
print(result)
// Your mark was 80%.
// That's 'Good'.
| [
-1
] |
72c94db4c5b61a9b09d6468576b5ca67948179b7 | dec1b9babbbc4bd8c7d6a02594456aa819f6aab9 | /YTDemo/ChannelPlaylists/ChannelPlaylistsResponse/PageInfo.swift | 130be01903e6d7abd71206bce52e9b6fc1587f16 | [] | no_license | yasmine-ghazy/YoutubeDemo | 0c2cf3e7dfdc1de2e2dbc6cd7765ccc832de30c7 | 996670f927ac816cbba7ef7dca767112ac91ba6f | refs/heads/master | 2020-04-12T04:32:23.201169 | 2018-12-18T14:55:55 | 2018-12-18T14:55:55 | 162,298,429 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 800 | swift | //
// PageInfo.swift
//
// Create by Waleed Ghalwash on 8/8/2018
// Copyright © 2018. All rights reserved.
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
// The "Swift - Struct - Gloss" support has been made available by CodeEagle
// More about him/her can be found at his/her website: https://github.com/CodeEagle
import Foundation
import Gloss
//MARK: - PageInfo
public struct PageInfo: Glossy {
public let resultsPerPage : Int!
public let totalResults : Int!
//MARK: Decodable
public init?(json: JSON){
resultsPerPage = "resultsPerPage" <~~ json
totalResults = "totalResults" <~~ json
}
//MARK: Encodable
public func toJSON() -> JSON? {
return jsonify([
"resultsPerPage" ~~> resultsPerPage,
"totalResults" ~~> totalResults,
])
}
} | [
-1
] |
8ad5e27f54c5b584f6b0ac1cc3709ff1a9837fa2 | 2b65c8017763e6ff410a431232597d01efadb2aa | /sceneKitDemo/LinkScene.swift | fd7cee5cced864a37b0d06a0d17ec9825aa592cb | [] | no_license | zxtcko/imageRecognition | 8b9b926364e071c2da6bcdb4ca6f59c46492a652 | bea6de9bb78aaf58dc207e087ea15f61fc5ba423 | refs/heads/master | 2021-01-20T20:05:10.703925 | 2016-08-01T08:35:37 | 2016-08-01T08:35:37 | 64,631,611 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,755 | swift | //
// LinkScene.swift
// sceneKitDemo
//
// Created by Chris on 16/7/5.
// Copyright © 2016年 Young. All rights reserved.
//
import SceneKit
import SceneKit.ModelIO
class LinkScene: SCNScene {
override init() {
super.init()
let tubeGeometry = SCNTube(innerRadius: 0.9, outerRadius: 1.0, height: 2.5)
let tubeNode = SCNNode(geometry: tubeGeometry)
tubeNode.position = SCNVector3(x: 0.0, y: 0.0, z: 10.0)
tubeNode.name = "LC-Blue"
tubeGeometry.firstMaterial?.diffuse.contents = UIColor.blueColor()
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("57997d59ab0b5", ofType: "obj")!)
// let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("body", ofType: "obj")!)
// let url2 = NSURL(string: "http://chriscoder.me/images/body.obj")
let asset = MDLAsset(URL: url)
let object = asset.objectAtIndex(0)
let node = SCNNode(MDLObject: object)
self.rootNode.addChildNode(node)
let spot = SCNLight()
spot.type = SCNLightTypeSpot
spot.castsShadow = true
let spotNode = SCNNode()
spotNode.light = spot
spotNode.position = SCNVector3(x: 4, y: 7, z: 6)
let lookAt = SCNLookAtConstraint(target: node)
spotNode.constraints = [lookAt]
let move = CABasicAnimation(keyPath: "position.x")
move.byValue = 10
move.duration = 1.0
node.addAnimation(move, forKey: "slide right")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| [
-1
] |
c195d430f738efbd8a3b7109482d23a5344b611a | 27e74aa1826ffea1d392c4edd972d2791314375c | /Gravity Ball Lite/MenuButton.swift | a36f259021474861e1f122a8962d9872dc440d12 | [] | no_license | condaatje/GravityBallLite | a4a6ae72e36bc5efcc9a06581ad7d6d7070e5797 | b2b650b0641b3247702814d60589671ec8f07798 | refs/heads/master | 2021-01-19T13:00:39.436375 | 2015-04-21T01:44:17 | 2015-04-21T01:44:17 | 34,297,533 | 0 | 1 | null | null | null | null | UTF-8 | Swift | false | false | 550 | swift | //
// MenuButton.swift
// Gravity Ball Lite
//
// Created by Christian Ondaatje on 12/5/14.
// Copyright (c) 2014 P. Christian Ondaatje. All rights reserved.
//
import SpriteKit
class MenuButton: SKSpriteNode {
var sizingFactor: Float = 0.0
var touched = false
override init() {
let texture = SKTexture(imageNamed: "MenuButton")
super.init(texture: texture, color: nil, size: texture.size())
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| [
-1
] |
f9a32dffbb1104e1454321d942086e95db7bf805 | 841591889cba772ab5bb59bd93f0e9459b7da17f | /Module/InputAmount/InputAmount/Router/InputAmountRouter.swift | 802085ef468d8a37271e78610c7aa0c6220a900f | [] | no_license | swaxtic/zwallet | 75fac46994b4de4431621e8e04e5fa0d0fda0336 | 6d88ff57bd7cb094484d391e12ef12f5a5f928f5 | refs/heads/master | 2023-06-20T09:33:38.666458 | 2021-06-01T05:37:18 | 2021-06-01T05:37:18 | 384,347,682 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 330 | swift | //
// InputAmountRouter.swift
// InputAmount
//
// Created by MacBook on 28/05/21.
//
import Foundation
import UIKit
import Core
public protocol InputAmountRouter {
func navigateToReceiver(viewController: UIViewController)
func navigateToConfirmation(viewController: UIViewController, dataTransfer: TransferEntity)
}
| [
-1
] |
60b1a7042e76f1a05122d11720a508fb609b339e | 18fe0323a71cbc14ee78f7e1988da0d16a7d0f6f | /AR_MAP/SVProgressHUD+Ex.swift | ab062bfb23214f4a0c85ccf1b6ff787787ebcd0e | [] | no_license | anooptomar1/AR_Map | 8ac072e075b69420f33399e3f4e78b687a37cf29 | 1045dade7b38b11219659c159ed5ad2a331f2c55 | refs/heads/master | 2020-03-16T13:33:55.166141 | 2018-05-08T12:34:48 | 2018-05-08T12:34:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 450 | swift | //
// SVProgressHUD+Ex.swift
// AR_MAP
//
// Created by SeacenLiu on 2018/4/30.
// Copyright © 2018年 成. All rights reserved.
//
import Foundation
import SVProgressHUD
private let kSVDefaultDuration: TimeInterval = 1
extension SVProgressHUD {
class func showTip(status: String, duration: TimeInterval = kSVDefaultDuration) {
SVProgressHUD.showInfo(withStatus: status)
SVProgressHUD.dismiss(withDelay: duration)
}
}
| [
-1
] |
3fc602652c68b7b0c10cd64e688aef019f186209 | 3dd2eac06f2b68c1f84b2cf0f9ffb0595ccae4c0 | /FoodTracker/RatingControl.swift | feb66b2db3a35c2f7632c81cb1a7d26226c47270 | [] | no_license | KornSiwat/FoodTracker | 12d1d0b67bb922f8a786ce4957bb9e163aec7a14 | 7dcfa18a7e4309e07539fe152ddd1efc952f8af7 | refs/heads/master | 2020-06-12T10:16:57.551037 | 2019-06-28T12:21:03 | 2019-06-28T12:21:03 | 194,269,276 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,970 | swift | //
// RatingControl.swift
// FoodTracker
//
// Created by Siwat Ponpued on 6/27/19.
// Copyright © 2019 Siwat Ponpued. All rights reserved.
//
import UIKit
@IBDesignable class RatingControl: UIStackView {
private var ratingButtons: [UIButton] = []
@IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) {
didSet {
setupButtons()
}
}
@IBInspectable var starCount: Int = 5 {
didSet {
setupButtons()
}
}
var rating = 0 {
didSet {
updateButtonSelectionStates()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupButtons()
}
}
// MARK: - Setup
private extension RatingControl {
func setupButtons() {
removeExistingButton()
let buttons = createRatingButtons()
buttons.forEach { configButton(button: $0) }
updateButtonSelectionStates()
}
func removeExistingButton() {
ratingButtons.forEach { button in
removeArrangedSubview(button)
button.removeFromSuperview()
}
ratingButtons.removeAll()
}
func createRatingButtons() -> [UIButton] {
let filledStar = UIImage(named: "filledStar")
let emptyStar = UIImage(named: "emptyStar")
let highlightedStar = UIImage(named: "highlightedStar")
return (0..<starCount).map { _ in
let button = UIButton()
button.setImage(emptyStar, for: .normal)
button.setImage(filledStar, for: .selected)
button.setImage(highlightedStar, for: .highlighted)
button.setImage(highlightedStar, for: [.highlighted, .selected])
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true
button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true
return button
}
}
func configButton(button: UIButton) {
addArrangedSubview(button)
ratingButtons.append(button)
button.addTarget(self,
action: #selector(RatingControl.ratingButtonTapped(button:)),
for: .touchUpInside)
}
}
// MARK: - Button Action
private extension RatingControl {
@objc func ratingButtonTapped(button: UIButton) {
guard let index = ratingButtons.firstIndex(of: button) else {
fatalError("The button, \(button), is not in the ratingButtons array: \(ratingButtons)")
}
let selectedRating = index + 1
rating = (selectedRating == rating) ? 0 : selectedRating
}
func updateButtonSelectionStates() {
ratingButtons.enumerated().forEach { (index, button) in
button.isSelected = index < rating
}
}
}
| [
-1
] |
daa9e6c0c11d53ee793074efa4dc86f4d6a67669 | 8082a0f13e95889126d47a14dadf6e240cb01579 | /Test/TestTests/TestTests.swift | 73f31b7cae40af9411c9dbd1aaef6e05f1da489e | [] | no_license | ZihanZhang/INFO6350-Smartphones-Based-Web-Development-Assignments | 0ffb299bb31ce3b1f459b3ee32db588a0025c510 | e36c45365d5967c833722e499c1cd69e0525d61f | refs/heads/master | 2021-10-09T03:59:57.541246 | 2018-12-20T21:17:47 | 2018-12-20T21:17:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 963 | swift | //
// TestTests.swift
// TestTests
//
// Created by Zihan Zhang on 2017/10/21.
// Copyright © 2017年 Zihan Zhang. All rights reserved.
//
import XCTest
@testable import Test
class TestTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| [
360462,
98333,
16419,
229413,
204840,
278570,
344107,
155694,
253999,
229430,
319542,
180280,
163896,
352315,
376894,
286788,
352326,
311372,
196691,
278615,
385116,
237663,
254048,
319591,
131178,
221290,
278634,
278638,
319598,
352368,
204916,
131191,
237689,
131198,
278655,
278677,
196760,
426138,
278685,
311458,
278691,
49316,
32941,
278704,
377009,
278708,
131256,
295098,
139479,
254170,
229597,
311519,
205035,
286958,
327929,
344313,
147717,
368905,
180493,
254226,
368916,
262421,
377114,
237856,
237857,
278816,
311597,
98610,
180535,
336183,
278842,
287041,
287043,
311621,
139589,
319821,
254286,
344401,
377169,
368981,
155990,
368984,
106847,
98657,
270701,
246127,
270706,
139640,
246136,
106874,
246137,
311681,
311685,
106888,
385417,
385422,
213403,
385454,
377264,
278970,
311738,
33211,
319930,
336317,
336320,
311745,
278978,
254406,
188871,
278989,
278993,
278999,
328152,
369116,
188894,
287198,
279008,
279013,
279018,
319981,
279029,
254456,
279032,
377338,
377343,
279039,
254465,
287241,
279050,
139792,
303636,
393751,
254488,
279065,
377376,
180771,
377386,
197167,
385588,
352829,
115270,
377418,
385615,
426576,
369235,
295519,
139872,
66150,
344680,
295536,
287346,
139892,
287352,
344696,
279164,
189057,
311941,
336518,
279177,
369289,
311945,
344715,
311949,
287374,
377489,
311954,
352917,
230040,
271000,
377497,
303771,
221852,
377500,
205471,
344738,
139939,
279206,
295590,
287404,
295599,
205487,
303793,
336564,
164533,
287417,
303803,
287422,
66242,
377539,
287433,
287439,
164560,
385747,
279252,
361176,
418520,
287452,
295652,
369385,
230125,
312047,
312052,
230134,
172792,
344827,
221948,
279294,
205568,
295682,
197386,
434957,
295697,
426774,
197399,
426775,
336671,
344865,
197411,
262951,
279336,
295724,
353069,
312108,
197422,
164656,
353070,
262962,
295729,
328499,
353078,
230199,
353079,
197431,
336702,
295746,
353094,
353095,
353109,
377686,
230234,
189275,
435039,
279392,
295776,
303972,
385893,
246641,
246643,
295798,
246648,
361337,
279417,
254850,
369538,
287622,
295824,
189348,
353195,
140204,
353197,
377772,
304051,
230332,
377790,
353215,
353216,
213957,
213960,
345033,
279498,
386006,
418776,
50143,
123881,
320493,
320494,
304110,
287731,
271350,
295927,
312314,
304122,
328700,
320507,
328706,
410627,
320516,
295942,
386056,
230410,
353290,
377869,
320527,
238610,
418837,
140310,
197657,
238623,
336929,
369701,
345132,
238639,
312373,
238651,
377926,
238664,
353367,
156764,
156765,
304222,
230499,
173166,
312434,
377972,
353397,
377983,
279685,
402565,
222343,
386189,
296086,
238743,
296092,
238765,
279728,
238769,
402613,
279747,
353479,
353481,
353482,
402634,
189652,
189653,
419029,
148696,
296153,
279774,
304351,
304356,
222440,
328940,
279792,
353523,
386294,
386301,
320770,
386306,
279814,
328971,
312587,
353551,
320796,
222494,
353584,
345396,
386359,
116026,
378172,
222524,
279875,
312648,
230729,
337225,
304456,
222541,
296270,
238927,
353616,
296273,
222559,
378209,
230756,
386412,
230765,
296303,
279920,
312689,
296307,
116084,
337281,
148867,
378244,
296329,
296335,
9619,
370071,
279974,
173491,
304564,
353719,
361927,
296392,
370123,
148940,
280013,
312782,
222675,
353750,
280032,
271843,
280041,
361963,
296433,
321009,
280055,
288249,
296448,
230913,
230921,
329225,
296461,
304656,
329232,
370197,
402985,
394794,
230959,
288309,
312889,
288318,
280130,
124485,
288326,
288327,
280147,
239198,
157281,
99938,
312940,
222832,
247416,
337534,
337535,
263809,
288392,
239250,
419478,
345752,
255649,
337591,
321207,
296632,
280251,
321219,
280267,
403148,
9936,
9937,
370388,
272085,
345814,
280278,
280280,
18138,
67292,
345821,
321247,
321249,
345833,
345834,
288491,
280300,
239341,
67315,
173814,
313081,
124669,
288512,
288516,
280329,
321295,
321302,
345879,
116505,
321310,
255776,
247590,
362283,
378668,
296755,
321337,
280380,
345919,
436031,
403267,
280392,
345929,
255829,
18262,
362327,
280410,
370522,
345951,
362337,
345955,
296806,
288619,
288620,
280430,
214895,
313199,
362352,
313203,
124798,
182144,
305026,
67463,
329622,
337815,
124824,
214937,
214938,
239514,
436131,
354212,
436137,
362417,
124852,
288697,
362431,
214977,
280514,
214984,
362443,
247757,
346067,
280541,
329695,
436191,
313319,
337895,
247785,
296941,
436205,
329712,
362480,
313339,
43014,
354316,
313357,
182296,
305179,
239650,
223268,
354345,
223274,
124975,
346162,
124984,
288828,
436285,
288833,
288834,
436292,
403525,
436301,
338001,
354385,
338003,
223316,
280661,
329814,
338007,
354393,
280675,
280677,
43110,
321637,
313447,
436329,
288879,
223350,
280694,
215164,
313469,
215166,
280712,
215178,
346271,
436383,
362659,
239793,
125109,
182456,
379071,
149703,
338119,
346314,
321745,
387296,
280802,
379106,
338150,
346346,
321772,
125169,
338164,
436470,
125183,
149760,
411906,
125188,
313608,
125193,
125198,
272658,
125203,
125208,
305440,
125217,
338218,
321840,
379186,
125235,
280887,
125240,
321860,
182598,
289110,
305495,
215385,
272729,
379225,
321894,
280939,
354676,
199029,
436608,
362881,
240002,
436611,
248194,
395659,
395661,
240016,
108944,
190871,
149916,
420253,
141728,
289189,
108972,
272813,
338356,
436661,
281037,
289232,
281040,
256477,
281072,
174593,
420369,
289304,
207393,
182817,
289332,
174648,
338489,
338490,
322120,
281166,
297560,
354911,
436832,
436834,
191082,
313966,
420463,
281199,
346737,
313971,
346740,
420471,
330379,
330387,
117396,
117397,
346772,
330388,
264856,
314009,
289434,
346779,
338613,
166582,
289462,
314040,
158394,
363211,
289502,
363230,
264928,
338662,
330474,
346858,
289518,
125684,
199414,
35583,
363263,
322313,
322316,
117517,
322319,
166676,
207640,
289576,
191283,
273207,
289598,
420677,
355146,
355152,
355154,
281427,
281433,
355165,
355178,
330609,
207732,
158593,
240518,
224145,
355217,
256922,
289690,
420773,
289703,
363438,
347055,
289727,
273344,
330689,
363458,
379844,
19399,
338899,
330708,
248796,
248797,
207838,
347103,
314342,
289774,
347123,
240630,
314362,
257024,
330754,
330763,
281626,
248872,
322612,
314448,
339030,
314467,
281700,
257125,
322663,
281706,
207979,
273515,
404593,
363641,
363644,
150657,
248961,
330888,
363669,
339100,
380061,
339102,
199839,
429214,
330913,
265379,
249002,
306346,
3246,
421048,
339130,
265412,
290000,
298208,
298212,
298213,
290022,
330984,
298221,
298228,
216315,
208124,
388349,
363771,
437505,
322824,
257305,
126237,
339234,
109861,
372009,
412971,
298291,
306494,
216386,
224586,
372043,
331090,
314709,
314710,
372054,
159066,
314720,
281957,
314728,
306542,
380271,
314739,
208244,
314741,
249204,
290173,
306559,
314751,
298374,
314758,
314760,
142729,
388487,
314766,
306579,
282007,
290207,
314783,
314789,
282022,
314791,
282024,
396711,
396712,
241066,
380337,
380338,
150965,
380357,
339398,
306631,
306639,
413137,
429542,
191981,
290300,
290301,
282114,
372227,
306692,
323080,
323087,
175639,
282136,
388632,
396827,
282141,
134686,
282146,
306723,
347694,
290358,
265798,
282183,
265804,
396882,
290390,
306776,
44635,
396895,
323172,
282213,
323178,
224883,
314998,
323196,
175741,
339584,
224901,
282245,
282246,
290443,
323217,
282259,
298654,
282271,
282276,
298661,
323236,
282280,
224946,
306874,
110268,
224958,
282303,
274115,
306890,
241361,
282327,
298712,
298720,
12010,
282348,
323316,
282358,
282369,
175873,
339715,
323331,
323332,
216839,
339720,
282378,
372496,
323346,
282391,
249626,
282400,
339745,
241441,
257830,
421672,
282409,
282417,
200498,
282427,
315202,
307011,
282438,
216918,
241495,
282474,
241528,
339841,
282504,
315273,
315274,
110480,
372626,
380821,
282518,
282519,
298909,
118685,
298920,
323507,
290745,
290746,
274371,
151497,
372701,
298980,
380908,
282612,
290811,
282633,
241692,
102437,
315432,
102445,
233517,
176175,
282672,
241716,
225351,
315465,
315476,
307289,
200794,
315487,
356447,
45153,
307301,
438377,
315498,
299121,
233589,
266357,
422019,
241808,
381073,
323729,
233636,
299174,
233642,
405687,
184505,
299198,
258239,
389313,
299203,
299209,
372941,
282831,
266449,
356576,
176362,
307435,
438511,
381172,
184570,
184575,
381208,
282909,
299293,
151839,
282913,
233762,
217380,
151847,
282919,
332083,
332085,
332089,
315706,
282939,
241986,
438596,
332101,
323913,
348492,
323916,
323920,
250192,
348500,
168281,
332123,
323935,
332127,
242023,
242029,
160110,
242033,
291192,
340357,
225670,
332167,
242058,
373134,
291224,
242078,
283038,
61857,
315810,
315811,
61859,
381347,
340398,
61873,
61880,
283064,
291267,
127427,
127428,
283075,
324039,
373197,
176601,
242139,
160225,
242148,
291311,
233978,
291333,
340490,
283153,
258581,
291358,
283184,
234036,
234040,
315960,
348732,
242237,
70209,
348742,
70215,
348749,
340558,
381517,
332378,
201308,
111208,
184940,
373358,
389745,
209530,
373375,
152195,
348806,
152203,
184973,
316049,
316053,
111253,
111258,
111259,
176808,
299699,
299700,
422596,
422599,
291530,
225995,
242386,
422617,
422626,
234217,
299759,
299776,
242433,
291585,
430849,
291592,
62220,
422673,
430865,
291604,
422680,
283419,
283430,
152365,
422703,
422709,
152374,
242485,
160571,
430910,
160575,
160580,
299849,
283467,
381773,
201551,
242529,
349026,
357218,
275303,
308076,
242541,
209785,
177019,
185211,
308092,
398206,
291712,
381829,
316298,
308107,
308112,
349072,
209817,
324506,
324507,
390045,
185250,
324517,
283558,
185254,
316333,
316343,
373687,
349121,
373706,
316364,
340955,
340961,
324586,
340974,
316405,
349175,
201720,
127992,
357379,
324625,
308243,
316437,
201755,
300068,
357414,
300084,
324666,
308287,
21569,
218186,
300111,
341073,
439384,
250981,
300135,
316520,
300136,
316526,
357486,
144496,
300146,
300150,
291959,
300151,
160891,
341115,
300158,
349316,
349318,
373903,
169104,
177296,
308372,
185493,
283802,
119962,
300187,
300188,
300201,
300202,
373945,
259268,
283847,
62665,
283852,
283853,
259280,
316627,
333011,
357595,
234733,
292085,
234742,
292091,
128251,
316669,
439562,
292107,
242954,
414990,
251153,
177428,
349462,
382258,
300343,
382269,
193859,
177484,
406861,
259406,
234831,
251213,
120148,
283991,
357719,
374109,
292195,
333160,
284014,
243056,
316787,
357762,
112017,
234898,
259475,
275859,
112018,
357786,
251298,
333220,
316842,
374191,
210358,
284089,
292283,
415171,
292292,
300487,
300489,
366037,
210390,
210391,
210392,
210393,
144867,
54765,
251378,
308723,
300536,
300542,
210433,
366083,
259599,
316946,
308756,
398869,
374296,
374299,
308764,
349726,
431649,
349741,
169518,
431663,
194110,
235070,
349763,
218696,
292425,
243274,
128587,
333388,
333393,
349781,
300630,
128599,
235095,
333408,
374372,
300644,
415338,
243307,
54893,
325231,
366203,
325245,
194180,
415375,
153251,
300714,
210603,
300728,
415420,
333503,
218819,
259781,
333517,
333520,
333521,
333523,
325346,
153319,
325352,
284401,
325371,
194303,
284429,
243472,
366360,
284442,
325404,
325410,
341796,
399147,
431916,
317232,
300848,
259899,
325439,
153415,
341836,
415567,
325457,
317269,
341847,
350044,
300894,
128862,
284514,
276327,
292712,
325484,
423789,
292720,
325492,
276341,
300918,
341879,
317304,
333688,
194429,
112509,
55167,
325503,
333701,
243591,
350093,
325518,
243597,
333722,
350109,
300963,
292771,
333735,
415655,
284587,
292782,
317360,
243637,
301008,
153554,
219101,
292836,
292837,
317415,
325619,
432116,
333817,
292858,
415741,
333828,
358410,
399373,
317467,
145435,
292902,
325674,
129076,
243767,
358456,
309345,
227428,
194666,
260207,
432240,
284788,
333940,
292988,
292992,
333955,
415881,
104587,
235662,
325776,
317587,
284826,
333991,
333992,
284842,
153776,
227513,
301251,
309444,
194782,
301279,
317664,
227578,
243962,
375039,
309503,
375051,
325905,
325912,
211235,
432421,
211238,
358703,
358709,
260418,
227654,
6481,
366930,
366929,
6489,
391520,
383332,
416104,
383336,
211326,
317831,
227725,
252308,
178582,
293274,
39324,
121245,
317852,
285090,
375207,
342450,
334260,
293303,
293306,
293310,
416197,
129483,
342476,
317901,
326100,
285150,
342498,
358882,
334309,
195045,
391655,
432618,
375276,
309744,
301571,
342536,
342553,
416286,
375333,
293419,
244269,
375343,
236081,
23092,
375351,
244281,
301638,
309830,
293448,
55881,
416341,
309846,
244310,
416351,
268899,
39530,
301689,
244347,
326287,
375440,
334481,
227990,
342682,
318107,
318106,
318130,
383667,
293556,
342713,
285371,
285372,
285373,
285374,
39614,
318173,
375526,
285415,
342762,
342763,
293612,
154359,
228088,
432893,
162561,
285444,
383754,
310036,
326429,
293664,
326433,
400166,
293672,
318250,
318252,
285487,
375609,
293693,
252741,
293711,
244568,
244570,
301918,
293730,
351077,
342887,
211829,
228215,
269178,
211836,
400252,
359298,
359299,
260996,
113542,
416646,
228233,
392074,
228234,
56208,
400283,
318364,
310176,
310178,
310182,
293800,
236461,
252847,
326581,
326587,
326601,
359381,
433115,
343005,
130016,
64485,
326635,
203757,
187374,
383983,
318461,
293886,
277509,
293893,
433165,
384016,
146448,
277524,
293910,
433174,
326685,
252958,
252980,
203830,
359478,
302139,
359495,
277597,
302177,
392290,
253029,
285798,
228458,
351344,
187506,
285814,
285820,
392318,
187521,
384131,
285828,
302213,
285830,
302216,
228491,
228493,
285838,
162961,
326804,
187544,
351390,
302240,
343203,
253099,
253100,
318639,
294068,
367799,
294074,
113850,
64700,
228542,
302274,
367810,
343234,
244940,
228563,
195808,
310497,
228588,
253167,
302325,
228600,
261377,
228609,
245019,
253216,
130338,
130343,
261425,
351537,
286013,
286018,
113987,
146762,
294218,
294219,
318805,
425304,
294243,
163175,
327024,
327025,
327031,
318848,
294275,
253317,
384393,
368011,
318864,
318868,
318875,
310692,
245161,
310701,
286129,
286132,
228795,
425405,
302529,
302531,
163268,
425418,
302540,
310732,
64975,
310736,
327121,
228827,
286172,
310757,
187878,
343542,
343543,
286202,
359930,
286205,
302590,
294400,
228867,
253451,
253452,
359950,
146964,
253463,
286244,
245287,
245292,
286254,
425535,
196164,
56902,
228943,
179801,
196187,
343647,
310889,
204397,
138863,
188016,
294529,
229001,
310923,
188048,
302739,
425626,
229020,
302754,
245412,
229029,
40614,
40613,
40615,
286391,
384695,
319162,
327358,
286399,
302797,
212685,
212688,
384720,
302802,
245457,
286423,
278233,
278234,
294622,
278240,
212716,
212717,
360177,
229113,
286459,
278272,
319233,
360195,
278291,
278293,
294678,
286494,
409394,
319292,
360252,
360264,
188251,
376669,
245599,
425825,
425833,
417654,
188292,
253829,
294807,
376732,
311199,
319392,
294823,
327596,
294843,
188348,
237504,
294850,
384964,
163781,
344013,
212942,
212946,
24532,
294886,
253929,
327661,
278512,
311281,
311282
] |
3660b92f3c126cdcca3be3338efbddb4b7a71bff | ae1e252884c204ca14b1c529d0c3b99bc146864c | /U17/U17/Module/Comic/View/UReadBottomBar.swift | e8ad9d896b7559ec01297b420a63b4bb7f88f1f9 | [
"MIT"
] | permissive | spicyShrimp/U17 | 39922c3eb13c77b93fbf2e81133e666736ae1ed0 | 8369fbf60c4e240efddfab364f97de8789e98dd5 | refs/heads/master | 2023-07-09T01:35:26.352629 | 2023-05-04T07:19:44 | 2023-05-04T07:19:44 | 112,552,820 | 1,098 | 285 | MIT | 2023-02-28T02:12:46 | 2017-11-30T02:15:42 | Swift | UTF-8 | Swift | false | false | 2,087 | swift | //
// UReadBottomBar.swift
// U17
//
// Created by Charles on 2017/11/26.
// Copyright © 2017年 None. All rights reserved.
//
import UIKit
import SnapKitExtend
class UReadBottomBar: UIView {
lazy var menuSlider: UISlider = {
let mr = UISlider()
mr.thumbTintColor = UIColor.theme
mr.minimumTrackTintColor = UIColor.theme
mr.isContinuous = false
return mr
}()
lazy var deviceDirectionButton: UIButton = {
let dn = UIButton(type: .system)
dn.setImage(UIImage(named: "readerMenu_changeScreen_horizontal")?.withRenderingMode(.alwaysOriginal), for: .normal)
return dn
}()
lazy var lightButton: UIButton = {
let ln = UIButton(type: .system)
ln.setImage(UIImage(named: "readerMenu_luminance")?.withRenderingMode(.alwaysOriginal), for: .normal)
return ln
}()
lazy var chapterButton: UIButton = {
let cn = UIButton(type: .system)
cn.setImage(UIImage(named: "readerMenu_catalog")?.withRenderingMode(.alwaysOriginal), for: .normal)
return cn
}()
override init(frame: CGRect) {
super.init(frame: frame)
configUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configUI() {
addSubview(menuSlider)
menuSlider.snp.makeConstraints {
$0.left.right.top.equalToSuperview().inset(UIEdgeInsets(top: 10, left: 40, bottom: 10, right: 40))
$0.height.equalTo(30)
}
addSubview(deviceDirectionButton)
addSubview(lightButton)
addSubview(chapterButton)
let buttonArray = [deviceDirectionButton, lightButton, chapterButton]
buttonArray.snp.distributeViewsAlong(axisType: .horizontal, fixedItemLength: 60, leadSpacing: 40, tailSpacing: 40)
buttonArray.snp.makeConstraints {
$0.top.equalTo(menuSlider.snp.bottom).offset(10)
$0.bottom.equalToSuperview()
}
}
}
| [
-1
] |
c0a2f51aaf1c05bea725139e9e2d41a0252e9a5a | 2ff95191f9422a5f401a419323fbf6e9b0a51ed2 | /WidGet/DominantColor-master/DominantColor/Shared/INVector3SwiftExtensions.swift | c142dc4a7e6fc80aae429af59802a91301a0ce62 | [
"MIT"
] | permissive | CastIrony/WidGet | 29505c3ed3083aa4e0c86bcd4d2bf7be519972dc | aa43a3bd402e5170be69af9a0156d9ef4308c218 | refs/heads/main | 2023-05-24T07:53:37.120984 | 2021-06-16T05:47:06 | 2021-06-16T05:47:06 | 374,033,405 | 4 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 757 | swift | //
// INVector3SwiftExtensions.swift
// DominantColor
//
// Created by Indragie on 12/24/14.
// Copyright (c) 2014 Indragie Karunaratne. All rights reserved.
//
import GLKit
extension GLKVector3 {
func unpack() -> (Float, Float, Float) {
return (x, y, z)
}
static var identity: GLKVector3 {
return GLKVector3Make(0, 0, 0)
}
static func + (lhs: GLKVector3, rhs: GLKVector3) -> GLKVector3 {
return GLKVector3Make(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
}
static func / (lhs: GLKVector3, rhs: Float) -> GLKVector3 {
return GLKVector3Make(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs)
}
static func / (lhs: GLKVector3, rhs: Int) -> GLKVector3 {
return lhs / Float(rhs)
}
}
| [
-1
] |
e7908916c7e003dd0c3affb1915625d6117e28fa | eb1775a5f164660278b3db0935d0555c333d55e6 | /Sources/BallStory.playground/Sources/PlayButton.swift | 9b84d960e9ef420c0391e9dbe696c624861019c3 | [] | no_license | adilsontavares/wwdc18-scholarship | 761acb56f0551ea1f2317f94a10f9e4b2532f710 | d5646bfbc6f250931568de2aca793682e099f485 | refs/heads/master | 2020-03-08T11:43:42.777638 | 2018-04-04T18:52:44 | 2018-04-04T18:52:44 | 128,106,344 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,362 | swift | import SpriteKit
public class PlayButton: SKSpriteNode {
enum State: String {
case idle = "play-button"
case playing = "stop-button"
case stopped = "restart-button"
}
public override var isUserInteractionEnabled: Bool {
didSet { alpha = isUserInteractionEnabled ? 1 : 0.4 }
}
var state: State = .idle
public init() {
let texture = SKTexture(imageNamed: "play-button")
super.init(texture: texture, color: .white, size: texture.size())
setup()
}
public required init?(coder: NSCoder) {
fatalError("Not implemented")
}
func setup() {
zPosition = 50
isUserInteractionEnabled = true
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let scene = self.scene as? GameScene else { return }
switch state {
case .idle:
state = .playing
scene.play()
case .playing:
state = .stopped
scene.pause()
case .stopped:
state = .idle
scene.restart()
}
updateTexture()
}
func updateTexture() {
let texture = SKTexture(imageNamed: state.rawValue)
self.texture = texture
}
}
| [
-1
] |
890c36d91a8463d41d5b8778286de4139aceeb73 | 35663839dca92da49f176d63631751c704ffed5f | /QuizApp/QuizApp/Services/LoginAPI.swift | a0221900b74384cf05e2b90fab03fe400de2fbbb | [] | no_license | domagojKo/Vjestina2020 | 9472f8a13e21649c5de29a05a54d8561f2bdb9c4 | 84e24fa8e0048f950085877b72f06cd843ab2351 | refs/heads/master | 2022-11-13T02:49:53.324106 | 2020-06-30T10:01:43 | 2020-06-30T10:01:43 | 261,585,033 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,655 | swift | //
// LoginAPI.swift
// QuizApp
//
// Created by Domagoj Kolaric on 06/05/2020.
// Copyright © 2020 Domagoj Kolaric. All rights reserved.
//
import Foundation
class LoginAPI {
typealias FetchTokenCompletion = ((Token?, Error?) -> Void)
static let instance = LoginAPI()
func fetchToken(username: String, password: String, completion: @escaping FetchTokenCompletion) {
guard let url = URL(string: "https://iosquiz.herokuapp.com/api/session") else {
completion(nil, nil)
return
}
let parameter = ["username" : username, "password" : password]
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameter, options: []) else {
return
}
request.httpBody = httpBody
let task = URLSession.shared.dataTask(with: request) {data, response, error in
guard let data = data,
let _ = response as? HTTPURLResponse,
error == nil else {
completion(nil, error)
return
}
do {
let decoder = JSONDecoder()
let model = try decoder.decode(Token.self, from:
data)
completion(model, nil)
} catch let parsingError {
print("Errorrrrrrr!")
completion(nil, parsingError)
}
}
task.resume()
}
}
| [
-1
] |
6c7e867613eda8a91b752eaad22817562a118388 | c81487d03649e5bca4e0b0189def6ef723baf089 | /Sources/SashaCore/Models/IconFactory.swift | 5bfe13b709aa51eac8babb17d4e880aa3b3c0c43 | [
"MIT"
] | permissive | gugell/sasha | 37c44b44d22b729501d19280a6be48f7cc378ff2 | d089ab5f5466090e452e31656015484b7ede5b64 | refs/heads/master | 2020-03-10T06:11:33.938948 | 2018-03-27T02:44:23 | 2018-03-27T02:44:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 5,035 | swift | //
// Copyright © 2017 Artem Novichkov. All rights reserved.
//
import Foundation
final class IconFactory {
/// Makes a set of icons. The set contains an icons only for selected idioms.
///
/// - Parameters:
/// - name: The name of generated icons.
/// - idioms: The idioms of icons.
/// - Returns: The set of icons.
func makeSet(withName name: String, idioms: [Icon.Idiom]) -> IconSet {
var icons = [Icon]()
idioms.forEach { idiom in
icons.append(contentsOf: makeIcons(forName: name, idiom: idiom))
}
return IconSet(icons: icons)
}
/// Makes a set of icons. The set contains an icons only for selected idiom.
///
/// - Parameters:
/// - name: The name of generated icons.
/// - idiom: The idiom of icons.
/// - Returns: The array of generated icons.
private func makeIcons(forName name: String, idiom: Icon.Idiom) -> [Icon] {
switch idiom {
case .iphone:
return [Icon(size: 20, idiom: idiom, filename: name, scale: 2),
Icon(size: 20, idiom: idiom, filename: name, scale: 3),
Icon(size: 29, idiom: idiom, filename: name, scale: 2),
Icon(size: 29, idiom: idiom, filename: name, scale: 3),
Icon(size: 40, idiom: idiom, filename: name, scale: 2),
Icon(size: 40, idiom: idiom, filename: name, scale: 3),
Icon(size: 60, idiom: idiom, filename: name, scale: 2),
Icon(size: 60, idiom: idiom, filename: name, scale: 3)]
case .ipad:
return [Icon(size: 20, idiom: idiom, filename: name, scale: 1),
Icon(size: 20, idiom: idiom, filename: name, scale: 2),
Icon(size: 29, idiom: idiom, filename: name, scale: 1),
Icon(size: 29, idiom: idiom, filename: name, scale: 2),
Icon(size: 40, idiom: idiom, filename: name, scale: 1),
Icon(size: 40, idiom: idiom, filename: name, scale: 2),
Icon(size: 76, idiom: idiom, filename: name, scale: 1),
Icon(size: 76, idiom: idiom, filename: name, scale: 2),
Icon(size: 83.5, idiom: idiom, filename: name, scale: 2)]
case .iosMarketing:
return [Icon(size: 1024, idiom: idiom, filename: name, scale: 1)]
case .carplay:
return [Icon(size: 60, idiom: idiom, filename: name, scale: 2),
Icon(size: 60, idiom: idiom, filename: name, scale: 3)]
case .mac:
return [Icon(size: 16, idiom: idiom, filename: name, scale: 1),
Icon(size: 16, idiom: idiom, filename: name, scale: 2),
Icon(size: 32, idiom: idiom, filename: name, scale: 1),
Icon(size: 32, idiom: idiom, filename: name, scale: 2),
Icon(size: 128, idiom: idiom, filename: name, scale: 1),
Icon(size: 128, idiom: idiom, filename: name, scale: 2),
Icon(size: 256, idiom: idiom, filename: name, scale: 1),
Icon(size: 256, idiom: idiom, filename: name, scale: 2),
Icon(size: 512, idiom: idiom, filename: name, scale: 1),
Icon(size: 512, idiom: idiom, filename: name, scale: 2)]
case .watch:
return [Icon(size: 24, idiom: idiom, filename: name, scale: 2, role: .notificationCenter, subtype: .mm38),
Icon(size: 27.5, idiom: idiom, filename: name, scale: 2, role: .notificationCenter, subtype: .mm42),
Icon(size: 29, idiom: idiom, filename: name, scale: 2, role: .companionSettings),
Icon(size: 29, idiom: idiom, filename: name, scale: 3, role: .companionSettings),
Icon(size: 40, idiom: idiom, filename: name, scale: 2, role: .appLauncher, subtype: .mm38),
Icon(size: 86, idiom: idiom, filename: name, scale: 2, role: .quickLook, subtype: .mm38),
Icon(size: 98, idiom: idiom, filename: name, scale: 2, role: .quickLook, subtype: .mm42)]
case .watchMarketing:
return [Icon(size: 1024, idiom: idiom, filename: name, scale: 1)]
}
}
/// Makes an array of icons for Android. The names of icons contain full paths including needed folders.
///
/// - Returns: The array of icons.
func makeAndroidIcons() -> [AndroidIcon] {
return [AndroidIcon(size: 72, name: "mipmap-hdpi/ic_launcher.png"),
AndroidIcon(size: 36, name: "mipmap-ldpi/ic_launcher.png"),
AndroidIcon(size: 48, name: "mipmap-mdpi/ic_launcher.png"),
AndroidIcon(size: 96, name: "mipmap-xhdpi/ic_launcher.png"),
AndroidIcon(size: 144, name: "mipmap-xxhdpi/ic_launcher.png"),
AndroidIcon(size: 192, name: "mipmap-xxxhdpi/ic_launcher.png"),
AndroidIcon(size: 512, name: "playstore-icon.png")]
}
}
| [
-1
] |
db8a50e94b4a24b3903a0df24ba9ad2b15fe47be | 59d1c23ebc5fda8aebef9543ee0a152f80bd051d | /Tinder/Controllers/BaseTransition.swift | 7c4c26a7846d8b3c5c740d3a87d363752c65a086 | [
"Apache-2.0"
] | permissive | sanazkh/Tinder-Lab | b3b07358a1fb99b696d4a71407631b266ae9c392 | 15bd44076a375420d2ebcb9ccccd5081a2a571fc | refs/heads/master | 2020-04-03T19:09:10.513602 | 2018-10-31T07:33:11 | 2018-10-31T07:33:11 | 155,512,211 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,463 | swift | //
// BaseTransition.swift
// Tinder
//
// Created by Sanaz Khosravi on 10/31/18.
// Copyright © 2018 GirlsWhoCode. All rights reserved.
//
import Foundation
import UIKit
class BaseTransition: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
var duration: TimeInterval = 0.4
var isPresenting: Bool = true
var isInteractive: Bool = false
var transitionContext: UIViewControllerContextTransitioning!
var interactiveTransition: UIPercentDrivenInteractiveTransition!
// Use for interactive transition
var percentComplete: CGFloat = 0 {
didSet {
interactiveTransition.update(percentComplete)
}
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if isInteractive {
interactiveTransition = UIPercentDrivenInteractiveTransition()
interactiveTransition.completionSpeed = 0.99
} else {
interactiveTransition = nil
}
return interactiveTransition
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
self.transitionContext = transitionContext
if (isPresenting) {
containerView.addSubview(toViewController.view)
presentTransition(containerView: containerView, fromViewController: fromViewController, toViewController: toViewController)
} else {
dismissTransition(containerView: containerView, fromViewController: fromViewController, toViewController: toViewController)
}
}
func presentTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) {
}
func dismissTransition(containerView: UIView, fromViewController: UIViewController, toViewController: UIViewController) {
}
func finish() {
if isInteractive {
isInteractive = false
interactiveTransition.finish()
} else {
if isPresenting == false {
let fromViewController = transitionContext?.viewController(forKey: UITransitionContextViewControllerKey.from)!
fromViewController?.view.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
func cancel() {
if isInteractive {
isInteractive = false
interactiveTransition.cancel()
}
}
}
| [
-1
] |
44f5e5fba83cb0931f0fa98147c217d922a275b5 | c67993e58a4bc7531cb4ae573964a58bbc90298a | /AppOfThrones/Episodes/EpisodeDetailViewController.swift | 8cd0145c20ddc30e56d9fe1443579dd6d2ffeee6 | [] | no_license | gestionarlaweb/keepcoding-GameOfThrones | 2ccd95bdd9bb119d26ccfff1a1508a45489ad289 | cab805ed6e5fd3bf049884298280c2874aed723c | refs/heads/master | 2021-05-19T07:33:59.879202 | 2020-03-31T11:47:54 | 2020-03-31T11:47:54 | 251,587,524 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,800 | swift |
import UIKit
class EpisodeDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var table: UITableView!
var episode: Episode?
convenience init(withEpisode episode: Episode) {
self.init(nibName: "EpisodeDetailViewController", bundle: nil)
self.episode = episode
self.title = episode.name
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
func setupUI(){
self.title = "Episode Detail"
// Aquí REGISTRAR las dos celdas
// CELDA 1
let nibCellImage = UINib.init(nibName: "EpisodeDetImageCell", bundle: nil)
self.table.register(nibCellImage, forCellReuseIdentifier: "EpisodeDetImageCell" )
// CELDA 2
let nibCellInfo = UINib.init(nibName: "EpisodeDetailInfoCell", bundle: nil)
self.table.register(nibCellInfo, forCellReuseIdentifier: "EpisodeDetailInfoCell" )
self.table.delegate = self
self.table.dataSource = self
}
// MARK: - UITableViewDelegate
// Aplicar los protocolos de delegate y dataSource
// Altura de las celdas
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
// Selección - deselección de la celda
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
table.deselectRow(at: indexPath, animated: true)
}
// MARK: - UITableViewDataSource
// Número de secciones 2
private func nunmerOfSections(in table: UITableView) -> Int {
return 1
}
// Número de filas de la sección
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
// Eres la celda 0
if indexPath.row == 0 {
if let cell = table.dequeueReusableCell(withIdentifier: "EpisodeDetImageCell", for: indexPath) as?
EpisodeDetImageCell{
cell.setEpisode(episode!)
return cell
}
fatalError("Could not create Account cells")
}
// Eres la celda 1
if indexPath.row == 1 {
if let cell = table.dequeueReusableCell(withIdentifier: "EpisodeDetailInfoCell", for: indexPath) as? EpisodeDetailInfoCell{
cell.setEpisode2(episode!)
return cell
}
}
fatalError("Could not create Account cells")
}
}
| [
-1
] |
180494a2d124f7d68ed3bcc8e8da9acc769eee10 | 1cfa98249e4043b6e5b0a454e03426f5f46b60b7 | /FinalProject/ParkItBoi/ParkItBoi/FreeCarSpots.swift | 7fe21ded25da2cf50edeb1119a62c6be690bef73 | [] | no_license | cavancook/Cook-2019-Fall-iOS | d47fcb7fa744ab2106647352cfd3fb44ad83efae | ce6e7993f4cc0efb3d69962b3ff3c3ff35d6b7c5 | refs/heads/master | 2022-03-25T08:50:12.859668 | 2019-12-26T07:38:09 | 2019-12-26T07:38:09 | 205,273,365 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,437 | swift | //
// FreeCarSpots.swift
// ParkItBoi
//
// Created by Cavan Cook on 12/5/19.
// Copyright © 2019 Cavan Cook. All rights reserved.
//
import Foundation
import MapKit
import Contacts
class FreeCarSpots: NSObject, MKAnnotation {
let title: String?
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D
init(title: String, locationName: String, discipline: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.locationName = locationName
self.discipline = discipline
self.coordinate = coordinate
super.init()
}
var subtitle: String? {
return locationName
}
// Annotation right callout accessory opens this mapItem in Maps app
func mapItem() -> MKMapItem {
let addressDict = [CNPostalAddressStreetKey: subtitle!]
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = title
return mapItem
}
var markerTintColor: UIColor {
switch discipline {
case "Car":
return .red
case "Motorcycle":
return .cyan
case "Bike":
return .blue
default:
return .green
}
}
var imageName: String? {
if discipline == "Motorcycle" { return "Motorcycle" }
if discipline == "Bike" { return "Bike" }
return "Car"
}
}
| [
307005,
312775
] |
242277ca5029d7a583d9f6934ca65d6a2f05919c | e9100d654d6e78dbd85f6ae72d70673da9f7f5bc | /InvestImmo/InvestImmo/SavedProjects/View/DetailsSimulationTableViewCell.swift | a7ff3378ae2b69b3b20e68c8709f65f333ad3237 | [] | no_license | NlionDev/Project12 | 0a68d51fab3656e9403fe4ef2cce2042e05e41c2 | ad2d78bce1a184351963cd7e05d363cf72806ab6 | refs/heads/master | 2021-03-25T23:35:43.451405 | 2020-05-03T07:53:55 | 2020-05-03T07:53:55 | 247,655,120 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 509 | swift | //
// DetailsTableViewCell.swift
// InvestImmo
//
// Created by Nicolas Lion on 19/04/2020.
// Copyright © 2020 Nicolas Lion. All rights reserved.
//
import UIKit
class DetailsSimulationTableViewCell: UITableViewCell {
//MARK: - Outlets
@IBOutlet weak private var titleLabel: UILabel!
@IBOutlet weak private var resultLabel: UILabel!
//MARK: - Methods
func configure(title: String, result: String) {
titleLabel.text = title
resultLabel.text = result
}
}
| [
-1
] |
18aac5b69c958490379ddcdc2ad442113fa475c5 | a9e14949cf897716e8338c21d6ed673014bbae26 | /SwiftChainingDemo/AppDelegate.swift | ea099197ed0ab9eaad98b5b2660ca71c65a182aa | [] | no_license | liuzhuan66/SwiftChainingDemo | 082fb2c1891cfd0e4a95686610255b8c5e4ab704 | 6e9fe02badf38d5f5eaf95b4c518ec40b3b5e9b4 | refs/heads/master | 2021-06-01T17:20:52.326104 | 2016-09-24T07:26:00 | 2016-09-24T07:26:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,177 | swift | //
// AppDelegate.swift
// SwiftChainingDemo
//
// Created by Carl Chen on 9/13/16.
// Copyright © 2016 nswebfrog. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| [
229380,
229383,
229385,
294924,
229388,
278542,
229391,
327695,
278545,
229394,
278548,
229397,
229399,
229402,
278556,
229405,
278559,
229408,
278564,
294950,
229415,
229417,
327722,
237613,
229422,
360496,
229426,
237618,
229428,
311349,
286774,
286776,
319544,
286778,
204856,
229432,
352318,
286791,
237640,
286797,
278605,
311375,
163920,
237646,
196692,
319573,
311383,
319590,
311400,
278635,
303212,
278639,
131192,
278648,
237693,
303230,
327814,
303241,
131209,
417930,
303244,
311436,
319633,
286873,
286876,
311460,
311469,
32944,
327862,
286906,
327866,
180413,
286910,
131264,
286916,
295110,
286922,
286924,
286926,
319694,
286928,
131281,
278743,
278747,
295133,
155872,
319716,
237807,
303345,
286962,
131314,
229622,
327930,
278781,
278783,
278785,
237826,
319751,
278792,
286987,
319757,
311569,
286999,
319770,
287003,
287006,
287009,
287012,
287014,
287016,
287019,
311598,
287023,
262448,
311601,
295220,
287032,
155966,
319809,
319810,
278849,
319814,
311623,
319818,
311628,
229709,
319822,
287054,
278865,
229717,
196963,
196969,
139638,
213367,
106872,
319872,
311683,
319879,
311693,
65943,
319898,
311719,
278952,
139689,
278957,
311728,
278967,
180668,
311741,
278975,
319938,
278980,
98756,
278983,
319945,
278986,
319947,
278990,
278994,
311767,
279003,
279006,
188895,
172512,
287202,
279010,
279015,
172520,
319978,
279020,
172526,
311791,
279023,
172529,
279027,
319989,
172534,
180727,
164343,
279035,
311804,
287230,
279040,
303617,
287234,
279045,
172550,
303623,
172552,
320007,
287238,
279051,
172558,
279055,
303632,
279058,
303637,
279063,
279067,
172572,
279072,
172577,
295459,
172581,
295461,
279082,
311850,
279084,
172591,
172598,
279095,
172607,
172609,
172612,
377413,
172614,
172618,
303690,
33357,
287309,
303696,
279124,
172634,
262752,
254563,
172644,
311911,
189034,
295533,
172655,
172656,
352880,
295538,
189039,
172660,
287349,
189040,
189044,
287355,
287360,
295553,
172675,
295557,
311942,
303751,
287365,
352905,
311946,
279178,
287371,
311951,
287377,
172691,
287381,
311957,
221850,
287386,
230045,
172702,
287390,
303773,
172705,
287394,
172707,
303780,
164509,
287398,
205479,
279208,
287400,
172714,
295595,
279212,
189102,
172721,
287409,
66227,
303797,
189114,
287419,
303804,
328381,
287423,
328384,
172737,
279231,
287427,
312005,
312006,
107208,
172748,
287436,
107212,
172751,
287440,
295633,
172755,
303827,
279255,
172760,
287450,
303835,
279258,
189149,
303838,
213724,
312035,
279267,
295654,
279272,
230128,
312048,
312050,
230131,
189169,
205564,
303871,
230146,
328453,
295685,
230154,
33548,
312077,
295695,
295701,
230169,
369433,
295707,
328476,
295710,
230175,
295720,
303914,
279340,
205613,
279353,
230202,
312124,
328508,
222018,
295755,
377676,
148302,
287569,
303959,
230237,
279390,
230241,
279394,
303976,
336744,
303985,
303987,
328563,
279413,
303991,
303997,
295806,
295808,
295813,
304005,
320391,
304007,
213895,
304009,
304011,
230284,
304013,
295822,
279438,
189329,
295825,
304019,
189331,
58262,
304023,
304027,
279452,
234648,
410526,
279461,
279462,
304042,
213931,
230327,
304055,
287675,
230334,
304063,
238528,
304065,
213954,
189378,
156612,
295873,
213963,
197580,
312272,
304084,
304090,
320481,
304106,
320490,
312302,
328687,
320496,
304114,
295928,
320505,
312321,
295945,
230413,
295949,
197645,
320528,
140312,
295961,
238620,
197663,
304164,
304170,
304175,
238641,
312374,
238652,
238655,
230465,
238658,
336964,
132165,
296004,
205895,
320584,
238666,
296021,
402518,
336987,
230497,
296036,
296040,
361576,
205931,
296044,
279661,
205934,
164973,
312432,
279669,
337018,
189562,
279679,
304258,
279683,
222340,
66690,
205968,
296084,
238745,
304285,
238756,
205991,
222377,
165035,
337067,
238766,
165038,
230576,
238770,
304311,
230592,
312518,
279750,
230600,
230607,
148690,
320727,
279769,
304348,
279777,
304354,
296163,
320740,
279781,
304360,
320748,
279788,
279790,
304370,
296189,
320771,
312585,
296202,
296205,
230674,
320786,
230677,
296213,
296215,
320792,
230681,
230679,
214294,
304416,
230689,
173350,
312622,
296243,
312630,
222522,
296253,
222525,
296255,
312639,
230718,
296259,
378181,
296262,
230727,
238919,
296264,
320840,
296267,
296271,
222545,
230739,
312663,
222556,
337244,
230752,
312676,
230760,
173418,
148843,
410987,
230763,
230768,
296305,
312692,
230773,
304505,
304506,
181626,
181631,
148865,
312711,
312712,
296331,
288140,
288144,
230800,
304533,
337306,
288154,
288160,
173472,
288162,
288164,
279975,
304555,
370092,
279983,
173488,
288176,
279985,
312755,
296373,
312759,
337335,
288185,
279991,
222652,
312766,
173507,
296389,
222665,
230860,
312783,
288208,
230865,
288210,
370130,
288212,
222676,
288214,
280021,
239064,
329177,
288217,
280027,
288220,
288218,
239070,
288224,
280034,
288226,
280036,
288229,
280038,
288230,
288232,
370146,
320998,
288234,
288236,
288238,
288240,
288242,
296435,
288244,
288250,
296446,
321022,
402942,
148990,
296450,
206336,
230916,
230919,
214535,
230923,
304651,
304653,
370187,
230940,
222752,
108066,
296486,
296488,
157229,
239152,
230961,
157236,
288320,
288325,
124489,
280140,
280145,
288338,
280149,
288344,
280152,
239194,
280158,
403039,
370272,
181854,
239202,
312938,
280183,
280185,
280188,
280191,
116354,
280194,
280208,
280211,
288408,
280218,
280222,
419489,
190118,
198310,
321195,
296622,
321200,
337585,
296626,
296634,
296637,
419522,
313027,
280260,
419525,
206536,
280264,
206539,
206541,
206543,
263888,
313044,
280276,
321239,
280283,
313052,
18140,
288478,
313055,
419555,
321252,
313066,
288494,
280302,
280304,
313073,
321266,
419570,
288499,
288502,
280314,
288510,
124671,
67330,
280324,
198405,
288519,
280331,
198416,
280337,
296723,
116503,
321304,
329498,
296731,
321311,
313121,
313123,
304932,
321316,
280363,
141101,
165678,
280375,
321336,
296767,
288576,
345921,
280388,
337732,
304968,
280393,
280402,
173907,
313171,
313176,
280419,
321381,
296809,
296812,
313201,
1920,
255873,
305028,
280454,
247688,
280464,
124817,
280468,
239510,
280473,
124827,
214940,
247709,
214944,
280487,
313258,
321458,
296883,
124853,
214966,
296890,
10170,
288700,
296894,
190403,
296900,
280515,
337862,
165831,
280521,
231379,
296921,
354265,
354270,
239586,
313320,
354281,
231404,
124913,
165876,
321528,
239612,
313340,
288764,
239617,
313347,
288773,
313358,
305176,
321560,
313371,
354338,
305191,
223273,
313386,
354348,
124978,
215090,
124980,
288824,
288826,
321595,
378941,
313406,
288831,
288836,
67654,
280651,
354382,
288848,
280658,
215123,
354390,
288855,
288859,
280669,
313438,
149599,
280671,
149601,
321634,
149603,
223327,
329830,
280681,
313451,
223341,
280687,
149618,
215154,
313458,
280691,
313464,
329850,
321659,
280702,
288895,
321670,
215175,
141446,
288909,
141455,
141459,
280725,
313498,
100520,
288936,
280747,
288940,
288947,
280755,
321717,
280759,
280764,
280769,
280771,
280774,
280776,
313548,
321740,
280783,
280786,
280788,
313557,
280793,
280796,
280798,
338147,
280804,
280807,
157930,
280811,
280817,
125171,
157940,
280819,
182517,
280823,
280825,
280827,
280830,
280831,
280833,
125187,
280835,
125191,
125207,
125209,
321817,
125218,
321842,
223539,
125239,
280888,
280891,
289087,
280897,
280900,
305480,
239944,
280906,
239947,
305485,
305489,
379218,
280919,
248153,
354653,
313700,
313705,
280937,
190832,
280946,
223606,
313720,
280956,
239997,
280959,
313731,
199051,
240011,
289166,
240017,
297363,
190868,
240021,
297365,
297368,
297372,
141725,
297377,
289186,
297391,
289201,
240052,
289207,
289210,
305594,
281024,
289218,
289221,
289227,
281045,
281047,
215526,
166378,
305647,
281075,
174580,
240124,
281084,
305662,
305664,
240129,
305666,
305668,
223749,
240132,
281095,
223752,
150025,
338440,
330244,
223757,
281102,
223763,
223765,
281113,
322074,
281116,
281121,
182819,
281127,
150066,
158262,
158266,
289342,
281154,
322115,
158283,
281163,
281179,
338528,
338532,
281190,
199273,
281196,
19053,
158317,
313973,
297594,
281210,
158347,
264845,
182926,
133776,
314003,
117398,
314007,
289436,
174754,
330404,
289448,
133801,
174764,
314029,
314033,
240309,
133817,
314045,
314047,
314051,
199364,
297671,
158409,
256716,
289493,
363234,
289513,
289522,
289525,
289532,
322303,
289537,
322310,
264969,
322314,
322318,
281361,
281372,
322341,
215850,
281388,
289593,
281401,
289601,
281410,
281413,
281414,
240458,
281420,
240468,
281430,
322393,
297818,
281435,
281438,
281442,
174955,
224110,
207733,
207737,
158596,
183172,
338823,
322440,
314249,
240519,
183184,
142226,
289687,
240535,
297883,
289694,
289696,
289700,
289712,
281529,
289724,
52163,
183260,
281567,
289762,
322534,
297961,
183277,
281581,
322550,
134142,
322563,
314372,
330764,
175134,
322599,
322610,
314421,
281654,
314427,
314433,
207937,
314441,
207949,
322642,
314456,
281691,
314461,
281702,
281704,
314474,
281708,
281711,
289912,
248995,
306341,
306344,
306347,
322734,
306354,
142531,
199877,
289991,
306377,
289997,
249045,
363742,
363745,
298216,
330988,
126190,
216303,
322801,
388350,
257302,
363802,
199976,
199978,
314671,
298292,
298294,
257334,
216376,
380226,
298306,
224584,
224587,
224594,
216404,
306517,
150870,
314714,
224603,
159068,
314718,
265568,
314723,
281960,
150890,
306539,
314732,
314736,
290161,
216436,
306549,
298358,
314743,
306552,
290171,
314747,
306555,
298365,
290174,
224641,
281987,
298372,
314756,
281990,
224647,
265604,
298377,
314763,
142733,
298381,
314768,
224657,
306581,
314773,
314779,
314785,
314793,
282025,
282027,
241068,
241070,
241072,
282034,
241077,
150966,
298424,
306618,
282044,
323015,
306635,
306640,
290263,
290270,
290275,
339431,
282089,
191985,
282098,
290291,
282101,
241142,
191992,
290298,
151036,
290302,
282111,
290305,
175621,
306694,
192008,
323084,
257550,
290321,
282130,
323090,
290325,
282133,
241175,
290328,
282137,
290332,
241181,
282142,
282144,
290344,
306731,
290349,
290351,
290356,
28219,
282186,
224849,
282195,
282199,
282201,
306778,
159324,
159330,
314979,
298598,
323176,
224875,
241260,
323181,
257658,
315016,
282249,
290445,
282261,
175770,
298651,
282269,
323229,
298655,
323231,
61092,
282277,
306856,
196133,
282295,
323260,
282300,
323266,
282310,
323273,
282319,
306897,
241362,
306904,
282328,
298714,
52959,
216801,
282337,
241380,
216806,
323304,
282345,
12011,
282356,
323318,
282364,
282367,
306945,
241412,
323333,
282376,
216842,
323345,
282388,
323349,
282392,
184090,
315167,
315169,
282402,
315174,
323367,
241448,
315176,
241450,
282410,
306988,
306991,
315184,
323376,
315190,
241464,
159545,
282425,
298811,
118593,
307009,
413506,
307012,
241475,
298822,
148946,
315211,
282446,
307027,
315221,
323414,
315223,
241496,
241498,
307035,
307040,
110433,
282465,
241509,
110438,
298860,
110445,
282478,
315249,
110450,
315251,
282481,
315253,
315255,
339838,
315267,
282499,
315269,
241544,
282505,
241546,
241548,
298896,
298898,
282514,
241556,
298901,
44948,
241560,
282520,
241563,
241565,
241567,
241569,
282531,
241574,
282537,
298922,
36779,
241581,
282542,
241583,
323504,
241586,
282547,
241588,
290739,
241590,
241592,
241598,
290751,
241600,
241605,
151495,
241610,
298975,
241632,
298984,
241640,
241643,
298988,
241646,
241649,
241652,
323574,
290807,
299003,
241661,
299006,
282623,
315396,
241669,
315397,
282632,
282639,
290835,
282645,
241693,
282654,
241701,
102438,
217127,
282669,
323630,
282681,
290877,
282687,
159811,
315463,
315466,
192589,
307278,
192596,
176213,
307287,
307290,
217179,
315482,
192605,
315483,
233567,
299105,
200801,
217188,
299109,
307303,
315495,
356457,
45163,
307307,
315502,
192624,
307314,
323700,
299126,
233591,
299136,
307329,
307338,
233613,
241813,
307352,
299164,
241821,
299167,
315552,
184479,
184481,
315557,
184486,
307370,
307372,
184492,
307374,
307376,
299185,
323763,
184503,
176311,
299191,
307386,
258235,
307388,
307385,
307390,
176316,
299200,
184512,
307394,
299204,
307396,
184518,
307399,
323784,
233679,
307409,
307411,
176343,
299225,
233701,
307432,
184572,
282881,
184579,
282893,
291089,
282906,
291104,
233766,
295583,
176435,
307508,
315701,
332086,
307510,
307512,
168245,
307515,
307518,
282942,
282947,
323917,
110926,
282957,
233808,
323921,
315733,
323926,
233815,
315739,
323932,
299357,
242018,
242024,
299373,
315757,
250231,
242043,
315771,
299388,
299391,
291202,
299398,
242057,
291212,
299405,
291222,
315801,
283033,
242075,
291226,
194654,
61855,
291231,
283042,
291238,
291241,
127403,
127405,
291247,
299440,
127407,
299444,
127413,
283062,
291254,
127417,
291260,
283069,
127421,
127424,
299457,
127429,
127431,
127434,
315856,
176592,
315860,
176597,
283095,
127447,
299481,
176605,
242143,
127457,
291299,
340454,
127463,
242152,
291305,
127466,
176620,
127469,
127474,
291314,
291317,
127480,
135672,
291323,
233979,
127485,
291330,
283142,
127494,
127497,
233994,
135689,
127500,
291341,
233998,
127506,
234003,
234006,
127511,
152087,
283161,
242202,
234010,
135707,
135710,
242206,
242208,
291361,
242220,
291378,
152118,
234038,
234041,
315961,
70213,
242250,
111193,
242275,
299620,
242279,
168562,
184952,
135805,
135808,
291456,
373383,
299655,
135820,
316051,
225941,
316054,
299672,
135834,
373404,
299677,
225948,
135839,
299680,
225954,
299684,
135844,
242343,
209576,
242345,
373421,
135870,
135873,
135876,
135879,
299720,
299723,
299726,
225998,
226002,
119509,
226005,
226008,
299740,
242396,
201444,
299750,
283368,
234219,
283372,
226037,
283382,
316151,
234231,
234236,
226045,
242431,
234239,
209665,
234242,
299778,
242436,
226053,
234246,
226056,
234248,
291593,
242443,
234252,
242445,
234254,
291601,
234258,
242450,
242452,
234261,
348950,
201496,
234264,
234266,
234269,
283421,
234272,
234274,
152355,
299814,
234278,
283432,
234281,
234284,
234287,
283440,
185138,
242483,
234292,
234296,
234298,
160572,
283452,
234302,
234307,
242499,
234309,
316233,
234313,
316235,
234316,
283468,
234319,
242511,
234321,
234324,
185173,
201557,
234329,
234333,
308063,
234336,
242530,
349027,
234338,
234341,
234344,
234347,
177004,
234350,
324464,
234353,
152435,
177011,
234356,
234358,
234362,
234364,
291711,
234368,
291714,
234370,
291716,
234373,
316294,
201603,
226182,
308105,
234375,
324490,
226185,
234379,
234384,
234388,
234390,
324504,
234393,
209818,
308123,
324508,
234396,
291742,
226200,
234398,
234401,
291747,
291748,
234405,
291750,
234407,
324520,
324518,
324522,
234410,
291756,
291754,
226220,
324527,
291760,
234417,
201650,
324531,
234414,
234422,
226230,
324536,
275384,
234428,
291773,
242623,
324544,
234431,
234434,
324546,
324548,
234437,
226245,
234439,
226239,
234443,
291788,
234446,
275406,
193486,
234449,
316370,
193488,
234452,
234455,
234459,
234461,
234464,
234467,
234470,
168935,
5096,
324585,
234475,
234478,
316400,
234481,
316403,
234484,
234485,
234487,
324599,
234490,
234493,
316416,
234496,
308226,
234501,
308231,
234504,
234507,
234510,
234515,
300054,
316439,
234520,
234519,
234523,
234526,
234528,
300066,
234532,
300069,
234535,
234537,
234540,
144430,
234543,
234546,
275508,
300085,
234549,
300088,
234553,
234556,
234558,
316479,
234561,
316483,
160835,
234563,
308291,
234568,
234570,
316491,
234572,
300108,
234574,
300115,
234580,
234581,
242777,
234585,
275545,
234590,
234593,
234595,
234597,
300133,
234601,
300139,
234605,
160879,
234607,
275569,
234610,
316530,
300148,
234614,
398455,
144506,
234618,
234620,
275579,
234623,
226433,
234627,
275588,
234629,
242822,
234634,
234636,
177293,
234640,
275602,
234643,
308373,
226453,
234647,
275606,
275608,
234650,
308379,
324757,
300189,
324766,
119967,
234653,
324768,
234657,
283805,
242852,
300197,
234661,
283813,
234664,
177318,
275626,
234667,
316596,
308414,
234687,
300223,
300226,
308418,
234692,
300229,
308420,
308422,
283844,
226500,
300234,
283850,
300238,
300241,
316625,
300243,
300245,
316630,
300248,
300253,
300256,
300258,
300260,
234726,
300263,
300265,
300267,
161003,
300270,
300272,
120053,
300278,
275703,
316663,
300284,
275710,
300287,
292097,
300289,
161027,
300292,
300294,
275719,
234760,
177419,
300299,
242957,
300301,
283917,
177424,
275725,
349451,
349464,
415009,
283939,
259367,
292143,
283951,
300344,
226617,
243003,
283963,
226628,
300357,
283973,
177482,
283983,
316758,
357722,
316766,
316768,
292192,
218464,
292197,
316774,
243046,
218473,
284010,
136562,
324978,
275834,
333178,
275836,
275840,
316803,
316806,
226696,
316811,
226699,
316814,
226703,
300433,
234899,
300436,
226709,
357783,
316824,
316826,
144796,
300448,
144807,
144810,
144812,
284076,
144814,
227426,
144820,
374196,
284084,
292279,
284087,
144826,
144828,
144830,
144832,
144835,
144837,
38342,
144839,
144841,
144844,
144847,
144852,
144855,
103899,
300507,
333280,
218597,
292329,
300523,
259565,
300527,
308720,
259567,
292338,
226802,
316917,
292343,
308727,
300537,
316933,
316947,
308757,
308762,
284191,
316959,
284194,
284196,
235045,
284199,
284204,
284206,
284209,
284211,
194101,
284213,
316983,
194103,
284215,
308790,
284218,
226877,
292414,
284223,
284226,
284228,
292421,
226886,
284231,
128584,
243268,
284234,
366155,
317004,
276043,
284238,
226895,
284241,
194130,
284243,
300628,
284245,
292433,
284247,
317015,
235097,
243290,
276053,
284249,
284251,
300638,
284253,
284255,
243293,
284258,
292452,
292454,
284263,
177766,
284265,
292458,
284267,
292461,
284272,
284274,
284278,
292470,
276086,
292473,
284283,
276093,
284286,
292479,
284288,
292481,
284290,
325250,
284292,
292485,
276095,
276098,
284297,
317066,
284299,
317068,
284301,
276109,
284303,
284306,
276114,
284308,
284312,
284314,
284316,
276127,
284320,
284322,
284327,
284329,
317098,
284331,
276137,
284333,
284335,
276144,
284337,
284339,
300726,
284343,
284346,
284350,
358080,
276160,
284354,
358083,
284358,
276166,
358089,
284362,
276170,
284365,
276175,
284368,
276177,
284370,
358098,
284372,
317138,
284377,
276187,
284379,
284381,
284384,
358114,
284386,
358116,
276197,
317158,
358119,
284392,
325353,
358122,
284394,
284397,
358126,
276206,
358128,
284399,
358133,
358135,
276216,
358138,
300795,
358140,
284413,
358142,
358146,
317187,
284418,
317189,
317191,
284428,
300816,
300819,
317207,
284440,
300828,
300830,
276255,
300832,
325408,
300834,
317221,
227109,
358183,
186151,
276268,
300845,
243504,
300850,
284469,
276280,
325436,
358206,
276291,
366406,
276295,
300872,
292681,
153417,
358224,
284499,
276308,
284502,
317271,
178006,
276315,
292700,
317279,
284511,
227175,
292715,
300912,
292721,
284529,
300915,
284533,
292729,
317306,
284540,
292734,
325512,
169868,
276365,
317332,
358292,
284564,
284566,
399252,
350106,
284572,
276386,
284579,
276388,
358312,
317353,
284585,
276395,
292776,
292784,
276402,
358326,
161718,
358330,
276410,
276411,
276418,
276425,
301009,
301011,
301013,
292823,
358360,
301017,
301015,
292828,
276446,
153568,
276448,
276452,
292839,
276455,
292843,
276460,
292845,
276464,
178161,
227314,
276466,
325624,
276472,
317435,
276476,
276479,
276482,
276485,
317446,
276490,
350218,
292876,
350222,
317456,
276496,
317458,
178195,
243733,
243740,
317468,
317472,
325666,
243751,
292904,
276528,
243762,
309298,
325685,
325689,
235579,
325692,
235581,
178238,
276539,
276544,
284739,
325700,
243779,
292934,
243785,
276553,
350293,
350295,
309337,
194649,
227418,
350302,
227423,
350304,
178273,
309346,
194657,
194660,
350308,
309350,
309348,
292968,
309352,
309354,
301163,
350313,
350316,
227430,
301167,
276583,
350321,
276590,
284786,
276595,
350325,
252022,
227440,
350328,
292985,
301178,
350332,
292989,
301185,
292993,
350339,
317570,
317573,
350342,
350345,
350349,
301199,
317584,
325777,
350354,
350357,
350359,
350362,
350366,
276638,
284837,
153765,
350375,
350379,
350381,
350383,
129200,
350385,
350387,
350389,
350395,
350397,
350399,
227520,
350402,
227522,
301252,
350406,
227529,
301258,
309450,
276685,
309455,
276689,
309462,
301272,
276699,
194780,
309468,
309471,
301283,
317672,
317674,
325867,
243948,
194801,
227571,
309491,
309494,
243960,
276735,
227583,
227587,
276739,
211204,
276742,
227593,
227596,
325910,
309530,
342298,
211232,
317729,
276775,
211241,
325937,
325943,
211260,
260421,
276809,
285002,
276811,
235853,
276816,
235858,
276829,
276833,
391523,
276836,
293227,
276843,
293232,
276848,
186744,
211324,
227709,
285061,
366983,
317833,
178572,
285070,
285077,
178583,
227738,
317853,
276896,
317858,
342434,
285093,
317864,
285098,
276907,
235955,
276917,
293304,
293307,
293314,
309707,
293325,
317910,
293336,
235996,
317917,
293343,
358880,
276961,
227810,
293346,
276964,
293352,
236013,
293364,
301562,
293370,
317951,
309764,
301575,
121352,
293387,
236043,
342541,
317963,
113167,
55822,
309779,
317971,
309781,
277011,
55837,
227877,
227879,
293417,
227882,
309804,
293421,
105007,
236082,
285236,
23094,
277054,
244288,
129603,
301636,
318020,
301639,
301643,
277071,
285265,
399955,
309844,
277080,
309849,
285277,
285282,
326244,
318055,
277100,
309871,
121458,
277106,
170618,
170619,
309885,
309888,
277122,
227975,
277128,
285320,
301706,
318092,
326285,
334476,
318094,
277136,
277139,
227992,
334488,
318108,
285340,
318110,
227998,
137889,
383658,
285357,
318128,
277170,
293555,
318132,
342707,
154292,
277173,
285368,
277177,
277181,
318144,
277187,
277191,
277194,
277196,
277201,
342745,
137946,
342747,
342749,
113378,
203491,
228069,
277223,
342760,
285417,
56041,
56043,
277232,
228081,
56059,
310015,
285441,
310020,
285448,
310029,
228113,
285459,
277273,
293659,
326430,
228128,
285474,
293666,
228135,
318248,
277291,
318253,
293677,
285489,
301876,
293685,
285494,
301880,
285499,
301884,
310080,
293696,
277317,
277322,
277329,
162643,
310100,
301911,
277337,
301913,
301921,
400236,
236397,
162671,
326514,
310134,
236408,
15224,
277368,
416639,
416640,
113538,
310147,
416648,
39817,
187274,
277385,
301972,
424853,
277405,
277411,
310179,
293798,
293802,
236460,
277426,
276579,
293811,
293817,
293820,
203715,
326603,
342994,
276586,
293849,
293861,
228327,
228328,
318442,
228330,
228332,
326638,
277486,
351217,
318450,
293876,
293877,
285686,
302073,
121850,
293882,
302075,
285690,
244731,
293887,
277504,
277507,
277511,
293899,
277519,
293908,
302105,
293917,
293939,
318516,
277561,
277564,
310336,
7232,
293956,
277573,
228422,
293960,
310344,
277577,
277583,
203857,
293971,
310355,
310359,
236632,
277594,
138332,
277598,
203872,
277601,
285792,
310374,
203879,
310376,
228460,
318573,
203886,
187509,
285815,
367737,
285817,
302205,
285821,
392326,
285831,
253064,
294026,
302218,
285835,
162964,
384148,
187542,
302231,
285849,
302233,
285852,
302237,
285854,
285856,
302241,
285862,
277671,
302248,
64682,
277678,
294063,
294065,
302258,
277687,
294072,
318651,
294076,
277695,
318657,
244930,
302275,
130244,
302277,
228550,
302282,
310476,
302285,
302288,
310481,
302290,
203987,
302292,
302294,
310486,
302296,
384222,
310498,
285927,
318698,
302315,
195822,
228592,
294132,
138485,
228601,
204026,
228606,
204031,
64768,
310531,
285958,
138505,
228617,
318742,
204067,
277798,
130345,
277801,
113964,
285997,
277804,
285999,
277807,
113969,
277811,
318773,
318776,
277816,
286010,
277819,
294204,
417086,
277822,
286016,
302403,
294211,
384328,
277832,
277836,
294221,
294223,
326991,
277839,
277842,
277847,
277850,
179547,
277853,
146784,
277857,
302436,
277860,
294246,
327015,
310632,
327017,
351594,
277864,
277869,
277872,
351607,
310648,
277880,
310651,
277884,
277888,
310657,
351619,
294276,
310659,
327046,
277892,
253320,
310665,
318858,
277894,
277898,
277903,
310672,
351633,
277905,
277908,
277917,
310689,
277921,
130468,
228776,
277928,
277932,
310703,
277937,
310710,
130486,
310712,
277944,
310715,
277947,
302526,
228799,
277950,
277953,
302534,
310727,
245191,
64966,
163272,
277959,
277963,
302541,
277966,
302543,
310737,
277971,
228825,
163290,
277978,
310749,
277981,
277984,
310755,
277989,
277991,
187880,
277995,
310764,
286188,
278000,
228851,
310772,
278003,
278006,
40440,
212472,
278009,
40443,
286203,
310780,
40448,
228864,
286214,
228871,
302603,
65038,
302614,
302617,
286233,
302621,
286240,
146977,
187939,
40484,
294435,
40486,
286246,
294440,
40488,
294439,
294443,
40491,
294445,
278057,
310831,
245288,
286248,
40499,
40502,
212538,
40507,
40511,
40513,
228933,
327240,
40521,
286283,
40525,
40527,
212560,
400976,
228944,
40533,
147032,
40537,
40539,
40541,
278109,
40544,
40548,
40550,
40552,
286312,
40554,
286313,
310892,
40557,
40560,
188022,
122488,
294521,
343679,
294537,
310925,
286354,
278163,
302740,
122517,
278168,
179870,
327333,
229030,
212648,
278188,
302764,
278192,
319153,
278196,
302781,
319171,
302789,
294599,
278216,
294601,
302793,
343757,
212690,
319187,
286420,
278227,
229076,
286425,
319194,
278235,
278238,
229086,
286432,
294625,
294634,
302838,
319226,
286460,
278274,
302852,
278277,
302854,
294664,
311048,
352008,
319243,
311053,
302862,
319251,
294682,
278306,
188199,
294701,
319280,
278320,
319290,
229192,
302925,
188247,
188252,
237409,
229233,
294776,
360317,
294785,
327554,
360322,
40840,
40851,
294803,
188312,
294811,
237470,
319390,
40865,
319394,
294817,
294821,
311209,
180142,
343983,
294831,
188340,
40886,
319419,
294844,
294847,
237508,
393177,
294876,
294879,
294883,
393190,
294890,
311279,
278513,
237555,
311283,
278516,
278519,
237562
] |
6f39cebd2ace91d3573d00b346acfae2217bf8e6 | a829794dc3764ace49208bf3d24c960d01c79ec9 | /Football News/Football News/Cities Tab/View Controller/FNCitiesVC.swift | 11031a2376e711cca1ff69a0b6bc7c3c8db1169c | [] | no_license | mahnoorkashif/Football-News | 791901117338d285defc8d661cb8193e7ba45e40 | 68d65be307bc165ba41ecbca8471621388fa5cba | refs/heads/master | 2022-03-29T09:37:15.420863 | 2020-01-03T07:54:26 | 2020-01-03T07:54:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,492 | swift | //
// FNCitiesVC.swift
// Football News
//
// Created by Mahnoor Khan on 24/07/2019.
// Copyright © 2019 Mahnoor Khan. All rights reserved.
//
import UIKit
class FNCitiesVC: UIViewController {
// MARK: Properties and Outlets
var citiesVM : FNCitiesVM?
@IBOutlet weak var tableView : UITableView!
let constants : FNConstants = FNConstants()
override func viewDidLoad() {
super.viewDidLoad()
initViewModel()
registerProtocols()
}
}
extension FNCitiesVC {
/// Function to set delegate and data source for table view
func registerProtocols() {
tableView.delegate = self
tableView.dataSource = self
}
/// Function to initialize view model
func initViewModel() {
citiesVM = FNCitiesVM()
}
}
// MARK: Table View Functions Extension
extension FNCitiesVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return citiesVM?.itemCount ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: constants.CITY_IDENTIFIER) as? FNCityCell else { return UITableViewCell() }
if let cityObject = citiesVM?.itemAt(indexPath) {
cell.setCell(city: cityObject)
}
return cell
}
}
| [
-1
] |
e8c550f1d494a4b920d1d2a8f1931527061943b7 | 121f28de2e0994799a5f047654542c996c5a0b2b | /toyWebBrowser/SceneDelegate.swift | 837d2a46ff22d1329c5ecc87aaa20356209aae13 | [] | no_license | YuyuQianRice/webBrowserApp | 1c66978a544effafea3fc25df1893285a4fd2835 | 01e73d2b62d9d384cb4eda3af36beed16dc12b4d | refs/heads/main | 2023-03-25T05:58:33.080144 | 2021-03-24T07:30:10 | 2021-03-24T07:30:10 | 350,981,647 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,292 | swift | //
// SceneDelegate.swift
// toyWebBrowser
//
// Created by Yuyu Qian on 3/23/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| [
393221,
163849,
393228,
393231,
393251,
352294,
344103,
393260,
393269,
213049,
376890,
385082,
393277,
376906,
327757,
254032,
368728,
254045,
180322,
376932,
286845,
286851,
417925,
262284,
360598,
377003,
377013,
164029,
327872,
180418,
377030,
377037,
377047,
418008,
418012,
377063,
327915,
205037,
393457,
393461,
393466,
418044,
385281,
262405,
180491,
336140,
164107,
262417,
368913,
262423,
377118,
377121,
262437,
254253,
336181,
262455,
393539,
262473,
344404,
213333,
418135,
270687,
262497,
418145,
262501,
213354,
246124,
262508,
262512,
213374,
385420,
393613,
262551,
262553,
385441,
385444,
262567,
385452,
262574,
393649,
385460,
262587,
344512,
262593,
360917,
369119,
328180,
328183,
328190,
254463,
328193,
328207,
410129,
393748,
262679,
377372,
188959,
385571,
377384,
197160,
33322,
352822,
270905,
197178,
418364,
188990,
369224,
385610,
270922,
352844,
385617,
352865,
262761,
352875,
344694,
352888,
336513,
377473,
385671,
148106,
213642,
377485,
352919,
98969,
344745,
361130,
336556,
385714,
434868,
164535,
164539,
328379,
328387,
352969,
344777,
418508,
385743,
385749,
139998,
189154,
369382,
361196,
418555,
344832,
336644,
344837,
344843,
328462,
361231,
394002,
336660,
418581,
418586,
434971,
369436,
262943,
369439,
418591,
418594,
336676,
418600,
418606,
369464,
361274,
328516,
336709,
328520,
336712,
361289,
328523,
336715,
361300,
213848,
426842,
361307,
197469,
361310,
254813,
361318,
344936,
361323,
361335,
328574,
369544,
361361,
222129,
345036,
115661,
386004,
345046,
386012,
386019,
386023,
328690,
435188,
328703,
328710,
418822,
377867,
328715,
361490,
386070,
271382,
336922,
345119,
377888,
214060,
345134,
345139,
361525,
386102,
361537,
377931,
345172,
189525,
402523,
361568,
148580,
345200,
361591,
386168,
361594,
410746,
214150,
345224,
386187,
345247,
361645,
345268,
402615,
361657,
402636,
328925,
165086,
66783,
165092,
328933,
222438,
328942,
386286,
386292,
206084,
328967,
345377,
345380,
353572,
345383,
337207,
345400,
378170,
369979,
386366,
337230,
337235,
263509,
353634,
337252,
402792,
271731,
378232,
337278,
271746,
181639,
353674,
181644,
361869,
181650,
181655,
230810,
181671,
181674,
181679,
181682,
337330,
181687,
370105,
181691,
181697,
361922,
337350,
181704,
337366,
271841,
329192,
361961,
329195,
116211,
337399,
402943,
337416,
329227,
419341,
419345,
329234,
419351,
345626,
419357,
345631,
419360,
370208,
394787,
419363,
370214,
419369,
394796,
419377,
419386,
214594,
419401,
353868,
419404,
173648,
419408,
214611,
419412,
403040,
345702,
370298,
353920,
403073,
403076,
345737,
198282,
403085,
403092,
345750,
419484,
345758,
345763,
419492,
345766,
419498,
419502,
370351,
419507,
337588,
419510,
419513,
419518,
403139,
337607,
419528,
419531,
419536,
272083,
394967,
419543,
419545,
345819,
419548,
419551,
345829,
419560,
337643,
419564,
337647,
370416,
337671,
362249,
362252,
395022,
362256,
321300,
345888,
362274,
378664,
354107,
345916,
354112,
370504,
329545,
345932,
370510,
354132,
247639,
337751,
370520,
313181,
182110,
354143,
354157,
345965,
345968,
345971,
345975,
403321,
1914,
354173,
395148,
247692,
337809,
247701,
436127,
436133,
247720,
337834,
362414,
337845,
190393,
247760,
346064,
346069,
419810,
329699,
354275,
190440,
354314,
346140,
436290,
395340,
378956,
436307,
338005,
100454,
329833,
329853,
329857,
329868,
411806,
329886,
346273,
362661,
100525,
387250,
379067,
387261,
256193,
395467,
346317,
411862,
256214,
411865,
411869,
411874,
379108,
411877,
387303,
346344,
395496,
338154,
387307,
346350,
338161,
387314,
436474,
379135,
411905,
411917,
379154,
395539,
387350,
387353,
338201,
338212,
395567,
248112,
362823,
436556,
321880,
362844,
379234,
354674,
321911,
420237,
379279,
272787,
354728,
338353,
338382,
272849,
248279,
256474,
182755,
338404,
338411,
330225,
248309,
248332,
330254,
199189,
420377,
330268,
191012,
330320,
199250,
191069,
346722,
248427,
338544,
346736,
191093,
346743,
346769,
150184,
174775,
248505,
174778,
363198,
223936,
355025,
273109,
355029,
264919,
256735,
264942,
363252,
338680,
264965,
338701,
256787,
363294,
396067,
346917,
396070,
215854,
355123,
355141,
355144,
338764,
355151,
330581,
330585,
387929,
355167,
265056,
265059,
355176,
355180,
355185,
412600,
207809,
379849,
347082,
396246,
330711,
248794,
248799,
437219,
257009,
265208,
199681,
338951,
330761,
330769,
330775,
248863,
396329,
347178,
404526,
396337,
330803,
396340,
339002,
388155,
339010,
347208,
248905,
330827,
248915,
183384,
339037,
412765,
257121,
265321,
248952,
420985,
330890,
347288,
248986,
44199,
380071,
339118,
249018,
339133,
126148,
330959,
330966,
265433,
265438,
388320,
363757,
388348,
339199,
396552,
175376,
175397,
273709,
372016,
437553,
347442,
199989,
175416,
396601,
208189,
437567,
175425,
437571,
437576,
437584,
437588,
396634,
175451,
437596,
429408,
175458,
175461,
175464,
265581,
331124,
175478,
175487,
249215,
175491,
249219,
249225,
249228,
249235,
175514,
175517,
396703,
396706,
175523,
355749,
396723,
388543,
380353,
216518,
380364,
339406,
372177,
339414,
249303,
413143,
339418,
339421,
249310,
339425,
249313,
339429,
339435,
249329,
69114,
372229,
208399,
380433,
175637,
405017,
134689,
265779,
421442,
413251,
265796,
265806,
224854,
224858,
339553,
257636,
224871,
372328,
257647,
372338,
224885,
224888,
224891,
224895,
372354,
126597,
421509,
224905,
11919,
224911,
224914,
126611,
224917,
224920,
126618,
208539,
224923,
224927,
224930,
224933,
257705,
224939,
224943,
257713,
224949,
257717,
257721,
224954,
257725,
224960,
257733,
224966,
224970,
257740,
224976,
257745,
257748,
224982,
257752,
224987,
257762,
224996,
225000,
225013,
257788,
225021,
339711,
257791,
225027,
257796,
339722,
257802,
257805,
225039,
257808,
249617,
225044,
167701,
372500,
257815,
225049,
257820,
225054,
184096,
397089,
257825,
225059,
339748,
225068,
257837,
413485,
225071,
225074,
257843,
225077,
257846,
225080,
397113,
225083,
397116,
257853,
225088,
225094,
225097,
257869,
257872,
225105,
397140,
225109,
225113,
257881,
257884,
257887,
225120,
257891,
225128,
257897,
225138,
257909,
225142,
372598,
257914,
257917,
225150,
257922,
380803,
225156,
339845,
257927,
225166,
397201,
225171,
380823,
225176,
225183,
372698,
372704,
372707,
356336,
380919,
393215,
372739,
405534,
266295,
266298,
421961,
200786,
356440,
217180,
430181,
266351,
356467,
266365,
192640,
266375,
381069,
225425,
250003,
225430,
250008,
356507,
250012,
225439,
135328,
192674,
225442,
438434,
225445,
438438,
225448,
438441,
356521,
225451,
258223,
225456,
430257,
225459,
225462,
225468,
389309,
225472,
372931,
225476,
430275,
389322,
225485,
225488,
225491,
266454,
225494,
225497,
225500,
225503,
225506,
225511,
217319,
225515,
225519,
381177,
397572,
389381,
381212,
356638,
356641,
356644,
356647,
266537,
389417,
356650,
356656,
332081,
340276,
356662,
397623,
332091,
225599,
348489,
332107,
151884,
430422,
348503,
332118,
250201,
250203,
250211,
340328,
250217,
348523,
348528,
332153,
356734,
389503,
332158,
438657,
332162,
389507,
348548,
356741,
332175,
160152,
373146,
340380,
373149,
70048,
356783,
266688,
324032,
201158,
340452,
127473,
217590,
340473,
324095,
324100,
324103,
324112,
340501,
324118,
324122,
340512,
332325,
324134,
381483,
356908,
324141,
324143,
356917,
324150,
324156,
168509,
348734,
324161,
324165,
356935,
348745,
381513,
324171,
324174,
324177,
389724,
332381,
373344,
340580,
348777,
381546,
340628,
184983,
373399,
258723,
332455,
332460,
389806,
332464,
332473,
381626,
332484,
332487,
332494,
357070,
357074,
332512,
340724,
332534,
373499,
348926,
389927,
348979,
348983,
398141,
357202,
389971,
357208,
389979,
430940,
357212,
357215,
439138,
349041,
340850,
381815,
430967,
324473,
398202,
119675,
340859,
324476,
430973,
324479,
340863,
324482,
373635,
324485,
324488,
185226,
381834,
324493,
324496,
324499,
430996,
324502,
324511,
422817,
324514,
201638,
398246,
373672,
324525,
5040,
111539,
324534,
5047,
324539,
324542,
398280,
349129,
340942,
209874,
340958,
431073,
398307,
340964,
209896,
201712,
209904,
349173,
381947,
201724,
349181,
431100,
431107,
349203,
209944,
209948,
357411,
250917,
169002,
357419,
209966,
209969,
209973,
209976,
209980,
209988,
209991,
431180,
209996,
349268,
177238,
250968,
210011,
373853,
341094,
210026,
210028,
210032,
349296,
210037,
210042,
210045,
349309,
152704,
349313,
160896,
210053,
210056,
349320,
259217,
373905,
210068,
210072,
210078,
210081,
210085,
210089,
210096,
210100,
324792,
210108,
357571,
210116,
210128,
210132,
333016,
210139,
210144,
218355,
218361,
275709,
128254,
275713,
242947,
275717,
275723,
333075,
349460,
349486,
349492,
415034,
210261,
365912,
259423,
374113,
251236,
374118,
390518,
357756,
374161,
112021,
349591,
357793,
333222,
259516,
415168,
366035,
415187,
366039,
415192,
415194,
415197,
415200,
333285,
415208,
366057,
366064,
415217,
415225,
423424,
415258,
415264,
366118,
415271,
382503,
349739,
144940,
415279,
415282,
415286,
210488,
415291,
415295,
349762,
333396,
374359,
333400,
366173,
423529,
423533,
210547,
415354,
333440,
267910,
267929,
259789,
366301,
333535,
153311,
366308,
366312,
431852,
399086,
366319,
210673,
366322,
399092,
366326,
333566,
268042,
210700,
366349,
210707,
399129,
333595,
210720,
366384,
358192,
210740,
366388,
358201,
325441,
366403,
325447,
341831,
341839,
341844,
415574,
358235,
350046,
399200,
399208,
268144,
358256,
358260,
399222,
325494,
333690,
325505,
399244,
333709,
333725,
333737,
382891,
382898,
350153,
358348,
333777,
219094,
399318,
358372,
350190,
350194,
333819,
350204,
350207,
325633,
325637,
350214,
219144,
268299,
333838,
350225,
186388,
350232,
333851,
350238,
350241,
374819,
350245,
350249,
350252,
178221,
350257,
350260,
350272,
243782,
350281,
350286,
374865,
252021,
342134,
374904,
268435,
333998,
334012,
260299,
211161,
375027,
358645,
268553,
268560,
432406,
325920,
194854,
358701,
391469,
358705,
358714,
358717,
383307,
358738,
383331,
383334,
391531,
383342,
334204,
268669,
194942,
391564,
366991,
334224,
342431,
375209,
375220,
334263,
326087,
358857,
195041,
334312,
104940,
375279,
416255,
350724,
186898,
342546,
350740,
342551,
342555,
416294,
350762,
252463,
358962,
334397,
358973,
252483,
219719,
399957,
334425,
326240,
375401,
334466,
334469,
391813,
162446,
342680,
342685,
260767,
342711,
244410,
260798,
334530,
260802,
350918,
154318,
342737,
391895,
154329,
416476,
64231,
113389,
203508,
375541,
342777,
391938,
391949,
375569,
375572,
375575,
375580,
162592,
334633,
326444,
383794,
375613,
244542,
260925,
375616,
342857,
416599,
342875,
244572,
433001,
400238,
211826,
211832,
392061,
351102,
252801,
260993,
351105,
400260,
211846,
342921,
342931,
252823,
400279,
392092,
400286,
252838,
359335,
211885,
252846,
400307,
351169,
359362,
351172,
170950,
187335,
326599,
359367,
359383,
359389,
383968,
343018,
261109,
261112,
244728,
383999,
261130,
261148,
359452,
211999,
261155,
261160,
261166,
359471,
375868,
343132,
384099,
384102,
384108,
367724,
187503,
343155,
384115,
212095,
351366,
384136,
384140,
384144,
351382,
384152,
384158,
384161,
351399,
384169,
367795,
244917,
384182,
367801,
384189,
384192,
351424,
343232,
367817,
244938,
384202,
253132,
384209,
146644,
351450,
384225,
359650,
343272,
351467,
359660,
384247,
351480,
384250,
351483,
351492,
384270,
359695,
261391,
253202,
261395,
384276,
384284,
245021,
384290,
253218,
245032,
171304,
384299,
351535,
245042,
326970,
384324,
212296,
212304,
367966,
343394,
367981,
343410,
155000,
327035,
245121,
245128,
253321,
155021,
384398,
245137,
245143,
245146,
245149,
245152,
245155,
155045,
245158,
114093,
327090,
343478,
359867,
384444,
327108,
327112,
384457,
359887,
359891,
368093,
155103,
343535,
343540,
368120,
409092,
253445,
359948,
359951,
245295,
359984,
343610,
400977,
400982,
179803,
155241,
155255,
155274,
368289,
245410,
425639,
425652,
425663,
155328,
245463,
155352,
155356,
155364,
245477,
155372,
245487,
212723,
409336,
155394,
155404,
245528,
155423,
360224,
155439,
204592,
155444,
155448,
417596,
384829,
360262,
155463,
155477,
376665,
155484,
261982,
425823,
155488,
376672,
155492,
327532,
261997,
376686,
262000,
262003,
425846,
262006,
147319,
262009,
327542,
262012,
155517,
155523,
155526,
360327,
376715,
155532,
262028,
262031,
262034,
262037,
262040,
262043,
155550,
253854,
262046,
262049,
262052,
327590,
155560,
155563,
155566,
327613,
393152,
393170,
155604,
155620,
253924,
155622,
253927,
327655,
360432,
393204,
360439,
253944,
393209,
155647
] |
043ab68ebbcf21e4226d909bc6de510fbf69badf | 6101958dea2057459ab844529864e40797bd36f5 | /CarOli/CarOli/TestViewController.swift | 962f290e1007a797dd6e29cf5001c5367293ed4d | [
"Apache-2.0"
] | permissive | freyzou/Unit-UITesting | a31d6eae4532f3210ad9d935460842411e9fa7d0 | d5df8abb7882ed8da88c614956fc0d35180559cb | refs/heads/master | 2021-08-23T23:49:10.682060 | 2017-12-07T04:29:32 | 2017-12-07T04:29:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,751 | swift | //
// TestViewController.swift
// CarOli
//
// Created by zz on 05/12/2017.
// Copyright © 2017 Lesta. All rights reserved.
//
import UIKit
class TestViewController: UIViewController {
let cellID = "TableViewCell"
override func viewDidLoad() {
super.viewDidLoad()
setupTable()
// Do any additional setup after loading the view.
}
@IBOutlet var tableView: UITableView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupTable() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
tableView.tableFooterView = UIView()
tableView.dataSource = self
tableView.register(UINib.init(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
}
/*
// 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.
}
*/
}
extension TestViewController:UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as? TableViewCell else { fatalError("Fuck") }
// cell.label.text = "sgwegwe"
return cell
}
}
| [
-1
] |
37fc436d48aabe06d7fb89116cb463acf23293aa | 339dc91ff254ea8c06463c909f4b7b4ee303f3c8 | /FoodBook/MyPage/MyPageViewController.swift | d0a652d2ec1125ac8c29616dbf7994fcd949e94d | [] | no_license | injun0701/foodBook | 568b60e9e1986e77ba1d356c03c2c5d8f27dc08e | 23dbee95645c97cdae8ec60d4a932dd4b3c098e0 | refs/heads/main | 2023-05-07T04:00:32.033087 | 2021-05-28T14:07:15 | 2021-05-28T14:07:15 | 365,075,257 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 15,980 | swift | //
// MyPageViewController.swift
// FoodBook
//
// Created by HongInJun on 2021/05/19.
//
import UIKit
class MyPageViewController: UIViewController {
@IBOutlet var imgView: UIImageView!
@IBOutlet var lblUserId: UILabel!
@IBOutlet var lblUserName: UILabel!
@IBOutlet var lblMyItemCount: UILabel!
@IBOutlet var tableView: UITableView!
//현재 출력한 체이지 번호를 저장할 프로퍼티
var page = 1
//마지막 셀이 처음 보여진 것인지 여부를 설정하는 프로퍼티
var flag = false
//서버 통신을 위한 객체
let req = URLRequest()
//테이블 뷰에 출력할 데이터 배열
var itemList: [Item] = []
//검색 결과 개수
var searchItemCountAll = 0
//정보 수정으로 이동
@IBAction func btnToMyPageEditAction(_ sender: UIButton) {
let sb = UIStoryboard(name: "MyPage", bundle: nil)
let navi = sb.instantiateViewController(withIdentifier: "MyPageEditViewController") as! MyPageEditViewController
navi.userImg = imgView.image!
navi.userId = lblUserId.text!
navi.userName = lblUserName.text!
navigationController?.pushViewController(navi, animated: true)
}
//좋아요 누른 게시판으로 이동
@IBAction func btnToItemLikeAction(_ sender: UIButton) {
let sb = UIStoryboard(name: "MyPage", bundle: nil)
let navi = sb.instantiateViewController(withIdentifier: "ItemLikeListViewController") as! ItemLikeListViewController
navigationController?.pushViewController(navi, animated: true)
}
//로그아웃 버튼
@IBAction func btnLogoutAction(_ sender: UIButton) {
showAlertBtn2(title: "로그아웃 안내", message: "로그아웃 하시겠습니까?", btn1Title: "취소", btn2Title: "로그아웃") {
} btn2Action: {
//로그아웃
self.logout()
}
}
//글쓰기 버튼
@IBAction func btnAddAction(_ sender: UIButton) {
LoadingHUD.show()
let sb = UIStoryboard(name: "ItemList", bundle: nil)
let navi = sb.instantiateViewController(withIdentifier: "ItemListPostViewController") as! ItemListPostViewController
let userImgUrl = UserDefaults.standard.value(forKey: UDkey().userimgurl)
let userName = UserDefaults.standard.value(forKey: UDkey().username)
navi.userImgUrl = userImgUrl as! String
navi.userName = userName as! String
navi.mode = "저장"
LoadingHUD.hide()
self.navigationController?.pushViewController(navi, animated: true)
}
//MARK: viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//네비 세팅
naviSetting()
tableViewSetting()
}
//네비게이션 세팅
func naviSetting() {
navbarSetting(title: "내 정보")
//네비게이션 오른쪽 버튼 - Search 뷰로 이동 버튼
let btnConfig: UIButton = UIButton(type: UIButton.ButtonType.custom)
btnConfig.setImage(UIImage(named: "config"), for: [])
btnConfig.addTarget(self, action: #selector(btnConfigAction), for: UIControl.Event.touchUpInside)
btnConfig.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let btnConfigItem = UIBarButtonItem(customView: btnConfig)
//네비게이션 오른쪽 버튼 - 햄버거 메뉴 생성
let btnSideMenu: UIButton = UIButton(type: UIButton.ButtonType.custom)
btnSideMenu.setImage(UIImage(named: "menu"), for: [])
btnSideMenu.addTarget(self, action: #selector(btnSideMenuAction), for: UIControl.Event.touchUpInside)
btnSideMenu.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let btnSideMenuItem = UIBarButtonItem(customView: btnSideMenu)
navigationItem.rightBarButtonItems = [btnSideMenuItem, btnConfigItem]
}
//설정 페이지로 이동
@objc func btnConfigAction() {
let sb = UIStoryboard(name: "SettingPage", bundle: nil)
let navi = sb.instantiateViewController(withIdentifier: "SettingPageViewController") as! SettingPageViewController
navigationController?.pushViewController(navi, animated: true)
}
//사이드 메뉴 호출
@objc func btnSideMenuAction() {
presentSideMenu()
}
//테이블뷰 세팅
func tableViewSetting() {
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(UINib(nibName: "ItemListTableViewCell", bundle: nil), forCellReuseIdentifier: "itemListTableViewCell")
//맨 위로 스크롤 했을때 리프레쉬 실행 객체를 테이블뷰에 추가
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
}
//MARK: viewWillAppear
override func viewWillAppear(_ animated: Bool) {
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
//뷰 세팅
viewSetting()
networkCheck { [self] in
//데이터 세팅
dataSetting(count: 10, searchKeyWord: userName ?? "")
}
}
//뷰 세팅
func viewSetting() {
let userId = UserDefaults.standard.value(forKey: UDkey().userid) as? String
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
lblUserId.text = userId
lblUserName.text = userName
//이미지 세팅
imgSetting()
}
//이미지 세팅
func imgSetting() {
let userImgUrl = UserDefaults.standard.value(forKey: UDkey().userimgurl) as? String
networkCheck() { [self] in
//유저 이미지 출력
req.getImg(imgurlName: userImgUrl!, defaultImgurlName: "userimg", toImg: imgView)
}
//유저이미지 라운드 처리
DispatchQueue.main.async { [self] in
imgView.layer.cornerRadius = imgView.frame.height/2
imgView.clipsToBounds = true
}
}
//데이터 세팅
func dataSetting(count: Int, searchKeyWord: String) {
LoadingHUD.show()
//서버에서 아이템 데이터 받아오기
req.apiItemGet(page: 1, count: count, searchKeyWord: searchKeyWord) { [self] noticheck, allcount, searchcount, list in
print(list)
itemList = [] //초기화
//페이지에서 가져온 데이터
if list.count != 0 {
//배열의 데이터 순회
for index in 0...(list.count - 1) {
//배열에서 하나씩 가져오기
let itemDict = list[index] as! [String: Any] //NSDictionary
//하나의 DTO 객체를 생성
var item = Item()
//json 파싱해서 객체에 데이터 대입
item.username = itemDict["username"] as? String
item.userimgurl = itemDict["userimgurl"] as? String
item.itemid = ((itemDict["itemid"] as! NSNumber).intValue)
item.itemname = itemDict["itemname"] as? String
item.price = ((itemDict["price"] as! NSNumber).intValue)
item.commentcount = ((itemDict["commentcount"] as! NSNumber).intValue)
item.likecount = ((itemDict["likecount"] as! NSNumber).intValue)
item.useritemlike = ((itemDict["useritemlike"] as! NSNumber).intValue)
item.description = itemDict["description"] as? String
item.imgurl = itemDict["imgurl"] as? String
item.updatedate = itemDict["updatedate"] as? String
//배열에 추가
itemList.append(item)
itemList.sort(by: {$0.itemid! > $1.itemid!}) //순서 정렬
}//반복문 종료
searchItemCountAll = searchcount
lblMyItemCount.text = "\(searchcount)"
tableView.reloadData()
//refreshControl 제거
refreshControl.endRefreshing()
}
LoadingHUD.hide()
NSLog("데이터 베이스 생성 성공")
} fail: {
LoadingHUD.hide()
self.showAlertBtn1(title: "데이터 오류", message: "데이터를 불러올 수 없습니다. 다시 시도해주세요.", btnTitle: "확인") {}
}
}
//refreshControl 객체 생성
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(ItemListViewController.handleRefresh(_:)), for: UIControl.Event.valueChanged)
refreshControl.tintColor = UIColor.lightGray
return refreshControl
}()
//맨 위로 스크롤 시 refesh 기능
@objc func handleRefresh(_ refreshControl: UIRefreshControl) {
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
networkCheck { [self] in
//데이터 세팅
dataSetting(count: 10, searchKeyWord: userName ?? "")
}
}
}
//MARK: 테이블뷰
extension MyPageViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//셀의 identifier로 사용할 문자열
let cellIdentifier = "itemListTableViewCell"
//재사용 가능한 셀이 있으면 찾아오기
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ItemListTableViewCell else {
return UITableViewCell()
}
let item = itemList[indexPath.row]
cell.lblUserName.text = item.username
//유저 이미지 출력
req.getImg(imgurlName: item.userimgurl!, defaultImgurlName: "userimg", toImg: cell.imgViewUser)
let itemDate = cutString(str: item.updatedate!, endIndex: 10, fromTheFront: true)
cell.lblDate.text = itemDate
cell.lblTitle.text = item.itemname
cell.lblText.text = item.description
cell.lblPrice.text = "\(item.price ?? 0)원"
cell.lblLike.text = "댓글: \(item.commentcount ?? 0), 좋아요: \(item.likecount ?? 0)"
//아이템 이미지 출력
req.getImg(imgurlName: item.imgurl!, defaultImgurlName: "gray", toImg: cell.imgViewlist)
if item.useritemlike == 1 { //좋아요한 상태
cell.btnLike.setImage(UIImage(named: "like_fill"), for: .normal)
//btnLikeTapHandler 작성
cell.btnLikeTapHandler = { [self] in
//네트워크 사용 여부 확인
networkCheck() {
itemLikeDelete(homePage: false, itemid: "\(item.itemid!)") {
let itemListCount = itemList.count
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
//데이터 세팅
dataSetting(count: itemListCount, searchKeyWord: userName ?? "")
} fail: {
let itemListCount = itemList.count
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
//데이터 세팅
dataSetting(count: itemListCount, searchKeyWord: userName ?? "")
}
}
}
} else { //좋아요 안한 상태
cell.btnLike.setImage(UIImage(named: "like"), for: .normal)
//btnLikeTapHandler 작성
cell.btnLikeTapHandler = { [self] in
//네트워크 사용 여부 확인
networkCheck() {
itemLikeInsert(homePage: false, itemid: "\(item.itemid!)", itemUserName: item.username!) {
let itemListCount = itemList.count
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
//데이터 세팅
dataSetting(count: itemListCount, searchKeyWord: userName ?? "")
} fail: {
let itemListCount = itemList.count
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
//데이터 세팅
dataSetting(count: itemListCount, searchKeyWord: userName ?? "")
}
}
}
}
//유저이미지 라운드 처리
DispatchQueue.main.async {
cell.imgViewUser.layer.cornerRadius = cell.imgViewUser.frame.height/2
cell.imgViewUser.clipsToBounds = true
}
//선택했을 때 회색 배경 없음 설정
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//테이블 셀의 인덱스
let cellIndexPath = tableView.indexPathForSelectedRow
//현재 셀 불러오기
guard let currentCell = tableView.cellForRow(at: cellIndexPath!) as? ItemListTableViewCell else { return }
let item = itemList[indexPath.row]
LoadingHUD.show()
let sb = UIStoryboard(name: "Comment", bundle: nil)
let navi = sb.instantiateViewController(withIdentifier: "CommentListViewController") as! CommentListViewController
navi.itemId = "\(item.itemid!)"
navi.itemName = item.itemname!
navi.itemImg = currentCell.imgViewlist.image!
navi.itemImgUrl = item.imgurl!
navi.itemPrice = "\(item.price!)"
navi.itemDescription = item.description!
let itemDate = cutString(str: item.updatedate!, endIndex: 10, fromTheFront: true)
navi.itemDate = "\(itemDate)"
navi.itemLikeCount = "\(item.likecount!)"
navi.userImgUrl = item.userimgurl!
navi.userImg = currentCell.imgViewUser.image!
navi.userName = item.username!
LoadingHUD.hide()
self.navigationController?.pushViewController(navi, animated: true)
}
//테이블 뷰에서 스트롤을 하면 호출되는 메소드 (셀이 보여질때 호출되는 메소드)
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//처음 마지막 셀이 출력되면
if flag == false && indexPath.row == self.itemList.count - 1 {
flag = true
} else if flag == true && indexPath.row == self.itemList.count - 1 {
print("\(searchItemCountAll), \(itemList.count)")
//api db의 전체 데이터 갯수가 리스트 배열의 개수보다 크면 실행
if searchItemCountAll > self.itemList.count {
//네트워크 사용 여부 확인
networkCheck() { [self] in
LoadingHUD.show()
let userName = UserDefaults.standard.value(forKey: UDkey().username) as? String
searchScrollItemAdd(page: page, itemList: self.itemList, searchKeyWord: userName ?? "") { itemList in
self.itemList = itemList
self.tableView.reloadData()
LoadingHUD.hide()
}
LoadingHUD.hide()
page = page + 1
flag = false
}
}
}
}
}
| [
-1
] |
234cb0d222e46759dd8fee3392abad2421f6cb0a | d09030cdcf778baee1a3d555128c01ce73ecf9df | /Cosmostation/Controller/Main/VoteListViewController.swift | f794abbb6e47a286a382f5c28449649df1b76a48 | [
"MIT"
] | permissive | cosmostation/cosmostation-ios | fb9555104adb209b887f67c5c18bba13969a6956 | 44804dc57bca599714763498fefbecb352a7c6d8 | refs/heads/master | 2023-08-20T14:14:30.591945 | 2023-08-20T07:42:08 | 2023-08-20T07:42:08 | 423,346,509 | 30 | 25 | MIT | 2023-09-13T09:26:40 | 2021-11-01T05:21:00 | Swift | UTF-8 | Swift | false | false | 14,636 | swift | //
// VoteListViewController.swift
// Cosmostation
//
// Created by yongjoo on 05/03/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import UIKit
import Alamofire
import SafariServices
import GRPC
import NIO
class VoteListViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var voteTableView: UITableView!
@IBOutlet weak var emptyLabel: UILabel!
@IBOutlet weak var loadingImg: LoadingImageView!
@IBOutlet weak var layerMultiVote: UIView!
@IBOutlet weak var layerMultiVoteAction: UIStackView!
@IBOutlet weak var btnCancel: UIButton!
@IBOutlet weak var btnNext: UIButton!
@IBOutlet weak var btnMultiVote: UIButton!
var refresher: UIRefreshControl!
var mVotingPeriods = Array<MintscanV1Proposal>()
var mEtcPeriods = Array<MintscanV1Proposal>()
var mFilteredProposals = Array<MintscanV1Proposal>()
var mFilteredEtcProposals = Array<MintscanV1Proposal>()
var mCheckedPeriods = Array<MintscanV1Proposal>()
var mMyVotes = Array<MintscanMyVotes>()
var mSelectedProposalIds = Array<UInt64>()
var mToVoteList = Array<MintscanProposalDetail>()
var mFetchCnt = 0
var isSelectMode = false;
var isShowAll = false
override func viewDidLoad() {
super.viewDidLoad()
self.account = BaseData.instance.selectAccountById(id: BaseData.instance.getRecentAccountId())
self.chainType = ChainFactory.getChainType(account!.account_base_chain)
self.chainConfig = ChainFactory.getChainConfig(chainType)
self.voteTableView.delegate = self
self.voteTableView.dataSource = self
self.voteTableView.separatorStyle = UITableViewCell.SeparatorStyle.none
self.voteTableView.register(UINib(nibName: "ProposalVotingPeriodCell", bundle: nil), forCellReuseIdentifier: "ProposalVotingPeriodCell")
self.voteTableView.register(UINib(nibName: "ProposalEtcPeriodCell", bundle: nil), forCellReuseIdentifier: "ProposalEtcPeriodCell")
self.voteTableView.rowHeight = UITableView.automaticDimension
self.voteTableView.estimatedRowHeight = UITableView.automaticDimension
self.refresher = UIRefreshControl()
self.refresher.addTarget(self, action: #selector(onFetchProposals), for: .valueChanged)
self.refresher.tintColor = UIColor.font05
self.voteTableView.addSubview(refresher)
self.btnCancel.setTitle(NSLocalizedString("str_cancel", comment: ""), for: .normal)
self.btnNext.setTitle(NSLocalizedString("str_next", comment: ""), for: .normal)
self.btnMultiVote.setTitle(NSLocalizedString("str_multi_vote", comment: ""), for: .normal)
self.loadingImg.onStartAnimation()
self.onFetchProposals()
}
@objc func onFetchProposals() {
if (mFetchCnt > 0 ) { return }
self.mFetchCnt = 2
self.onFetchMintscanProposals()
self.onFetchMintscanMyVotes()
}
func onFetchFinished() {
self.mFetchCnt = self.mFetchCnt - 1
if (mFetchCnt <= 0) {
onUpdateViews()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
self.navigationController?.navigationBar.topItem?.title = NSLocalizedString("title_vote_list", comment: "")
self.navigationItem.title = NSLocalizedString("title_vote_list", comment: "")
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
let showAllBtn = UIButton(type: .system)
if (isShowAll) { showAllBtn.setImage(UIImage(named: "iconCheckBox"), for: .normal) }
else { showAllBtn.setImage(UIImage(named: "iconUnCheckedBox"), for: .normal) }
showAllBtn.setTitle("Show All", for: .normal)
showAllBtn.titleLabel?.font = Font_13_footnote
showAllBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0)
showAllBtn.sizeToFit()
showAllBtn.addTarget(self, action: #selector(onToggleShow(_:)), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: showAllBtn)
}
@objc func onToggleShow(_ button: UIButton) {
isShowAll = !isShowAll
if (isShowAll) { button.setImage(UIImage(named: "iconCheckBox"), for: .normal) }
else { button.setImage(UIImage(named: "iconUnCheckedBox"), for: .normal) }
self.onUpdateViews()
}
func onUpdateViews() {
if (isShowAll) {
mFilteredProposals = mVotingPeriods
mFilteredEtcProposals = mEtcPeriods
} else {
mFilteredProposals = mVotingPeriods.filter() { !$0.isScam() }
mFilteredEtcProposals = mEtcPeriods.filter() { !$0.isScam() }
}
if (mFilteredProposals.count > 1) {
self.layerMultiVote.isHidden = false
} else {
self.layerMultiVote.isHidden = true
}
if (isSelectMode) {
btnMultiVote.isHidden = true
layerMultiVoteAction.isHidden = false
} else {
btnMultiVote.isHidden = false
layerMultiVoteAction.isHidden = true
}
self.sortProposals()
if (mFilteredProposals.count > 0 || mEtcPeriods.count > 0) {
self.emptyLabel.isHidden = true
self.voteTableView.reloadData()
} else {
self.emptyLabel.isHidden = false
}
self.refresher.endRefreshing()
self.loadingImg.onStopAnimation()
self.loadingImg.isHidden = true
}
@IBAction func onClickBack(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func onClickStartSelect(_ sender: UIButton) {
isSelectMode = true
onUpdateViews()
}
@IBAction func onClickCancel(_ sender: UIButton) {
mSelectedProposalIds.removeAll()
isSelectMode = false
onUpdateViews()
}
@IBAction func onClickNext(_ sender: UIButton) {
if (!account!.account_has_private) {
self.onShowAddMenomicDialog()
return
}
if (mSelectedProposalIds.count <= 0) {
self.onShowToast(NSLocalizedString("error_no_selected_proposal", comment: ""))
return
}
if (BaseData.instance.mMyDelegations_gRPC.count <= 0) {
self.onShowToast(NSLocalizedString("error_no_bonding_no_vote", comment: ""))
return
}
if (!BaseData.instance.isTxFeePayable(chainConfig)) {
self.onShowToast(NSLocalizedString("error_not_enough_fee", comment: ""))
return
}
mToVoteList.removeAll()
showWaittingAlert()
mSelectedProposalIds.forEach { toVote in
onFetchMintscanProposalDetail(toVote)
}
}
func onStartVote() {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(600), execute: {
let txVC = UIStoryboard(name: "GenTx", bundle: nil).instantiateViewController(withIdentifier: "TransactionViewController") as! TransactionViewController
txVC.mProposals = self.mToVoteList
txVC.mType = TASK_TYPE_VOTE
self.navigationItem.title = ""
self.navigationController?.pushViewController(txVC, animated: true)
})
}
func numberOfSections(in tableView: UITableView) -> Int {
if (isSelectMode) {
return 1
}
return 2
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = CommonHeader(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
if (section == 0) {
view.headerTitleLabel.text = NSLocalizedString("str_voting_period", comment: "")
view.headerCntLabel.text = String(mFilteredProposals.count)
} else if (section == 1) {
view.headerTitleLabel.text = NSLocalizedString("str_vote_proposals", comment: "")
view.headerCntLabel.text = String(mFilteredEtcProposals.count)
}
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if (section == 0 && mFilteredProposals.count <= 0) { return 0 }
if (section == 1 && mFilteredEtcProposals.count <= 0) { return 0 }
return 30
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0) { return mFilteredProposals.count }
else if (section == 1) { return mFilteredEtcProposals.count }
else { return 0 }
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier:"ProposalVotingPeriodCell") as? ProposalVotingPeriodCell
let proposal = mFilteredProposals[indexPath.row]
cell?.onBindView(chainConfig, proposal, mMyVotes, isSelectMode, mSelectedProposalIds)
return cell!
} else {
let cell = tableView.dequeueReusableCell(withIdentifier:"ProposalEtcPeriodCell") as? ProposalEtcPeriodCell
let proposal = mFilteredEtcProposals[indexPath.row]
cell?.onBindView(chainConfig, proposal, mMyVotes)
return cell!
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (isSelectMode) {
if (indexPath.section == 0) {
let proposal = mFilteredProposals[indexPath.row]
if (self.mSelectedProposalIds.contains(proposal.id!)) {
if let index = self.mSelectedProposalIds.firstIndex(of: proposal.id!) {
self.mSelectedProposalIds.remove(at: index)
}
} else {
self.mSelectedProposalIds.append(proposal.id!)
}
self.voteTableView.reloadRows(at: [indexPath], with: .none)
}
} else {
if (indexPath.section == 0) {
let voteDetailVC = VoteDetailsViewController(nibName: "VoteDetailsViewController", bundle: nil)
voteDetailVC.proposalId = mFilteredProposals[indexPath.row].id!
self.navigationItem.title = ""
self.navigationController?.pushViewController(voteDetailVC, animated: true)
} else {
let proposal = mFilteredEtcProposals[indexPath.row]
onExplorerLink(proposal.id!)
}
}
}
func onExplorerLink(_ proposalId: UInt64) {
let link = WUtils.getProposalExplorer(chainConfig, proposalId)
guard let url = URL(string: link) else { return }
self.onShowSafariWeb(url)
}
func onFetchMintscanProposals() {
let url = BaseNetWork.mintscanProposals(self.chainConfig!)
let request = Alamofire.request(url, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:])
request.responseJSON { (response) in
switch response.result {
case .success(let res):
self.mVotingPeriods.removeAll()
self.mEtcPeriods.removeAll()
self.mFilteredProposals.removeAll()
self.mFilteredEtcProposals.removeAll()
if let responseDatas = res as? Array<NSDictionary> {
responseDatas.forEach { rawProposal in
let tempProposal = MintscanV1Proposal.init(rawProposal)
if (tempProposal.isVotingPeriod()) {
self.mVotingPeriods.append(tempProposal)
} else {
self.mEtcPeriods.append(tempProposal)
}
}
}
case .failure(let error):
print("onFetchMintscanProposal ", error)
}
self.onFetchFinished()
}
}
func onFetchMintscanMyVotes() {
let url = BaseNetWork.mintscanMyVotes(self.chainConfig!, self.account!.account_address)
let request = Alamofire.request(url, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:])
request.responseJSON { (response) in
switch response.result {
case .success(let res):
self.mMyVotes.removeAll()
if let responseDatas = res as? NSDictionary,
let rawVotes = responseDatas.object(forKey: "votes") as? Array<NSDictionary> {
rawVotes.forEach { rawVote in
self.mMyVotes.append(MintscanMyVotes.init(rawVote))
}
}
case .failure(let error):
print("onFetchMintscanMyVotes ", error)
}
self.onFetchFinished()
}
}
func onFetchMintscanProposalDetail(_ id: UInt64) {
let url = BaseNetWork.mintscanProposalDetail(chainConfig!, id)
let request = Alamofire.request(url, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:])
request.responseJSON { (response) in
switch response.result {
case .success(let res):
if let responseData = res as? NSDictionary {
self.mToVoteList.append(MintscanProposalDetail.init(responseData))
}
if (self.mToVoteList.count == self.mSelectedProposalIds.count) {
self.hideWaittingAlert()
self.onStartVote()
}
case .failure(let error):
print("onFetchMintscanProposalDetail ", error)
}
}
}
func sortProposals() {
self.mFilteredProposals.sort {
return $0.id! < $1.id! ? false : true
}
self.mEtcPeriods.sort {
return $0.id! < $1.id! ? false : true
}
self.mCheckedPeriods.sort {
return $0.id! < $1.id! ? false : true
}
}
}
| [
-1
] |
bca1c022770b87b18abfcdcf32469379a27157de | a74d32885167d69621e8453e35200865b918bede | /FiestaNew/SceneDelegate.swift | 399f46c505bed9b0dc48eb176cebd8d8f6aff671 | [] | no_license | Stance0102/FiestaNew | 2434d8ab1f0fe10d7ddd5d145f29edace8aaf9e7 | 1b14158fb9e6d10d4b28dbbe4a3a0984649c7b14 | refs/heads/main | 2023-01-07T20:19:45.776049 | 2020-11-08T17:53:22 | 2020-11-08T17:53:22 | 311,170,156 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,686 | swift | //
// SceneDelegate.swift
// FiestaNew
//
// Created by 李慶毅 on 2020/5/25.
// Copyright © 2020 Li Ching Yi. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| [
325633,
325637,
163849,
268299,
333838,
186388,
346140,
352294,
411691,
163892,
16444,
337980,
254020,
217158,
243782,
395340,
327757,
200786,
286804,
329816,
180314,
217180,
368736,
342113,
180322,
329833,
286833,
368753,
252021,
342134,
286845,
192640,
286851,
329868,
268435,
250008,
329886,
286880,
135328,
192674,
333989,
286889,
356521,
258223,
430257,
387250,
334012,
104636,
180418,
350411,
346317,
180432,
350417,
368854,
350423,
211161,
350426,
385243,
334047,
356580,
346344,
327915,
350449,
372977,
375027,
387314,
338161,
350454,
321787,
336124,
350459,
350462,
336129,
350465,
397572,
350469,
389381,
325895,
194829,
350477,
43279,
350481,
350487,
356631,
338201,
325915,
350491,
381212,
325918,
182559,
350494,
258333,
325920,
350500,
194854,
350505,
350510,
395567,
248112,
332081,
307507,
340276,
336181,
264502,
356662,
332091,
332098,
201030,
332107,
190797,
334162,
332118,
418135,
321880,
250201,
383323,
332126,
258399,
332130,
250211,
340328,
250217,
348523,
348528,
182642,
321911,
332153,
334204,
268669,
194942,
332158,
250239,
332162,
389507,
348548,
393613,
383375,
332175,
272787,
160152,
340380,
268702,
416159,
176545,
326059,
373169,
342453,
334263,
338363,
266688,
324032,
336326,
393671,
338387,
248279,
369119,
334306,
338404,
334312,
338411,
104940,
375279,
162289,
328178,
328180,
248309,
328183,
340473,
199165,
328190,
324095,
328193,
98819,
324100,
266757,
324103,
164362,
391691,
248332,
199182,
328207,
324112,
330254,
186898,
342546,
340501,
324118,
334359,
262679,
342551,
324122,
334364,
330268,
358942,
340512,
191012,
332325,
324134,
197160,
381483,
324141,
324143,
334386,
324156,
358973,
334397,
188990,
152128,
324161,
324165,
219719,
324171,
324174,
324177,
244309,
334425,
326240,
340580,
375401,
248427,
191085,
346736,
338544,
268922,
334466,
336517,
344710,
119432,
148106,
162446,
330384,
326291,
340628,
342685,
340639,
354975,
336549,
332455,
271018,
332460,
336556,
389806,
332464,
385714,
164535,
336568,
174775,
248505,
174778,
244410,
328379,
332473,
223936,
328387,
332484,
332487,
373450,
418508,
154318,
332494,
342737,
355029,
154329,
183006,
139998,
189154,
338661,
338665,
332521,
418540,
330479,
342769,
340724,
332534,
338680,
342777,
418555,
344832,
207620,
336644,
191240,
328462,
326417,
336660,
338712,
199455,
336676,
336681,
334633,
326444,
215854,
328498,
152371,
326452,
271154,
326455,
340792,
348983,
244542,
326463,
326468,
328516,
336709,
127815,
244552,
328520,
326474,
328523,
336712,
342857,
326479,
355151,
330581,
326486,
136024,
330585,
326494,
439138,
326503,
375657,
201580,
326508,
201583,
326511,
355185,
211826,
340850,
330612,
201589,
381815,
340859,
324476,
328574,
340863,
359296,
351105,
252801,
373635,
324482,
324488,
342921,
236432,
361361,
324496,
330643,
324502,
252823,
324511,
324514,
252838,
201638,
211885,
252846,
340910,
5040,
324525,
5047,
324539,
324542,
187335,
398280,
347082,
340940,
345046,
330711,
248794,
340958,
248799,
340964,
386023,
338928,
328690,
359411,
244728,
330750,
265215,
328703,
199681,
328710,
338951,
330761,
379915,
328715,
326669,
330769,
361490,
349203,
209944,
386074,
336922,
209948,
248863,
345119,
250915,
357411,
250917,
158759,
347178,
328747,
214060,
209966,
209969,
330803,
209973,
386102,
209976,
339002,
339010,
209988,
209991,
347208,
248905,
330827,
197708,
330830,
341072,
248915,
345172,
183384,
156762,
343132,
339037,
322660,
210028,
326764,
326767,
187503,
345200,
173170,
330869,
361591,
386168,
210042,
210045,
361599,
343168,
152704,
160896,
330886,
351366,
384136,
384140,
351382,
337048,
210072,
248986,
384152,
210078,
384158,
210081,
384161,
251045,
210085,
185512,
210089,
339118,
337072,
210096,
337076,
345268,
210100,
249015,
324792,
367801,
339133,
384189,
343232,
384192,
210116,
337093,
244934,
326858,
322763,
333003,
384202,
343246,
384209,
333010,
146644,
330966,
210139,
328925,
66783,
384225,
328933,
343272,
351467,
328942,
251123,
384247,
384250,
388348,
242947,
206084,
115973,
343307,
384270,
333075,
384276,
333079,
251161,
384284,
245021,
384290,
208167,
263464,
171304,
245032,
245042,
44343,
345400,
208189,
386366,
372035,
343366,
126279,
337224,
251211,
357710,
337230,
331089,
337235,
437588,
263509,
331094,
365922,
197987,
208228,
175458,
343394,
343399,
175461,
345449,
337252,
175464,
333164,
99692,
343410,
234867,
331124,
175478,
155000,
378232,
249210,
175484,
337278,
249215,
245121,
249219,
245128,
249225,
181644,
361869,
249228,
136591,
245137,
181650,
249235,
112021,
181655,
245143,
175514,
245146,
343453,
245149,
245152,
357793,
396706,
263585,
245155,
355749,
40358,
181671,
245158,
333222,
245163,
380333,
181679,
337330,
327090,
210357,
146878,
181697,
361922,
327108,
372166,
181704,
339401,
327112,
384457,
327116,
327118,
208338,
366035,
343509,
337366,
249310,
423393,
249313,
333285,
329195,
343540,
343545,
423424,
253445,
339464,
337416,
249355,
329227,
175637,
405017,
345626,
245275,
366118,
339504,
349748,
206397,
214594,
349762,
415301,
396874,
333387,
370254,
343631,
214611,
333400,
366173,
339553,
343650,
333415,
245358,
333423,
222831,
138865,
339572,
333440,
372354,
126597,
159375,
126611,
140955,
333472,
245410,
345763,
345766,
425639,
245415,
337588,
155323,
333499,
337601,
337607,
333512,
210632,
333515,
339664,
358100,
419543,
245463,
212700,
181982,
153311,
333535,
225000,
337643,
245487,
339696,
337647,
245495,
141052,
337661,
333566,
339711,
372481,
225027,
337671,
210696,
339722,
366349,
249617,
321300,
245528,
333593,
116512,
397089,
362274,
210720,
184096,
339748,
257834,
358192,
372533,
345916,
399166,
384831,
325441,
247618,
325447,
341831,
329545,
341835,
323404,
354124,
337743,
339795,
354132,
341844,
247639,
337751,
358235,
341852,
313181,
413539,
399208,
274281,
339818,
327532,
257902,
339827,
358260,
341877,
399222,
325494,
182136,
186233,
1914,
333690,
243584,
325505,
333699,
339845,
247692,
333709,
247701,
337814,
329625,
327590,
333737,
382898,
370611,
337845,
184245,
190393,
327613,
333767,
350153,
346059,
311244,
358348,
247760,
212945,
333777,
399318,
219094,
419810,
329699,
358372,
327655,
247790,
204785,
380919,
333819
] |
a016686d4aad2d161ab9851dfe07854a3ac03bf9 | 6aeeb8a8d875e64b7db1a0c29ad1a0a958dee494 | /JaredFramework/Entities.swift | 62e1773fa1c5a846279384279b91ed06dcfc9293 | [
"Apache-2.0"
] | permissive | vkedwardli/Jared | 78ed8feb82db17576f5689ab8ad4d94570563252 | 2bc7330785833d5794ad276032dfca73e5ad84a8 | refs/heads/master | 2020-12-28T01:37:48.558592 | 2019-12-29T07:04:40 | 2019-12-29T07:04:40 | 238,139,279 | 0 | 0 | Apache-2.0 | 2020-02-04T06:31:46 | 2020-02-04T06:31:45 | null | UTF-8 | Swift | false | false | 1,582 | swift | //
// Entities.swift
// JaredFramework
//
// Created by Zeke Snider on 2/3/19.
// Copyright © 2019 Zeke Snider. All rights reserved.
//
import Foundation
public protocol RecipientEntity: Codable {
var handle: String {get set}
}
public protocol SenderEntity: Codable {
var handle: String {get set}
var givenName: String? {get set}
}
public struct Person: SenderEntity, RecipientEntity, Codable, Equatable {
public var givenName: String?
public var handle: String
public var isMe: Bool = false
enum CodingKeys : String, CodingKey{
case handle
}
public init(handle: String) {
self.handle = handle
}
public init(givenName: String?, handle: String, isMe: Bool?) {
self.givenName = givenName
self.handle = handle
self.isMe = isMe ?? false
}
public static func == (lhs: Person, rhs: Person) -> Bool {
return lhs.givenName == rhs.givenName &&
lhs.handle == rhs.handle &&
lhs.isMe == rhs.isMe
}
}
public struct Group: RecipientEntity, Codable, Equatable {
public var name: String?
public var handle: String
public var participants: [Person]
public init(name: String?, handle: String, participants: [Person]) {
self.name = name
self.handle = handle
self.participants = participants
}
public static func == (lhs: Group, rhs: Group) -> Bool {
return lhs.name == rhs.name &&
lhs.handle == rhs.handle &&
lhs.participants == rhs.participants
}
}
| [
-1
] |
547735cb82aaa79753e963188734bcbb2414007e | 50da6044b25f19b939f514fc5eb011bac86ccd22 | /Lab 3/Picz/Picz/CollectionViewCell.swift | 171d64376791a5e8833a060cb40a73e83721fc90 | [] | no_license | fsobenes/AMAD | efb54a8e8619cbdc5a5fc47ea72d676e02976b7c | 36736c9a853e4f535b1f9092bdb15af03fe4b55c | refs/heads/master | 2020-12-18T13:29:13.453883 | 2020-05-06T22:14:15 | 2020-05-06T22:14:15 | 235,401,412 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 274 | swift | //
// CollectionViewCell.swift
// Picz
//
// Created by Fiorella Sobenes on 3/3/20.
// Copyright © 2020 Fiorella Sobenes. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
| [
159480,
321191
] |
3d9f698b4f243c6f21f87d8110f4aeaa9b3b3203 | 8f20e039a4b0d64ed9a266271e4225104af22b69 | /TestStackOverFlow/Utils/Extensions.swift | 0f29b7f52d3acaae0feca87b02eba53d5fa30384 | [] | no_license | fernandocardenasm/TestStackOverFlow | 2a987694d5d4bb88213bf07a20deb1de8ff0a244 | 0525135aebe79907748e9a91ba2c35261d630781 | refs/heads/master | 2020-03-18T13:12:55.635028 | 2018-06-03T16:52:12 | 2018-06-03T16:52:12 | 134,768,469 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,486 | swift | //
// Extensions.swift
// TestStackOverFlow
//
// Created by Fernando on 14.05.18.
// Copyright © 2018 Fernando. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func anchorSize(to view: UIView) {
widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, trailing: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top {
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let leading = leading {
leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
}
if let trailing = trailing {
trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true
}
if size.width != 0 {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0 {
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
}
| [
316960
] |
bd1c8e872a1b1c41c6b253ee03b2cc2d96695045 | ede7c1ddefd19e70913cc46c346bda26d103c7b7 | /PaymentSDK/Sources/Modules/Methods/PaymentMethodsProtocols.swift | baee21a38e00d8f438fadbac8fcf7768f5829f53 | [
"MIT"
] | permissive | tungnx-teko/payment-sdk-ios | 9781c98161690372f0a2cb4e11b427cfd3f037c9 | 4ceec69237ca613bf89428100e84d57103e66a4a | refs/heads/master | 2022-11-13T05:38:16.700587 | 2020-07-10T02:47:47 | 2020-07-10T02:47:47 | 276,837,866 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 891 | swift | //
// PaymentMethodsProtocols.swift
// Pods
//
// Created by Tung Nguyen on 7/2/20.
//
import Foundation
import PaymentGateway
protocol PaymentMethodDelegate: class {
func onResult(_ result: PaymentResult)
}
protocol PaymentMethodsViewProtocol: class {
var presenter: PaymentMethodsPresenterProtocol? { get }
func showAmount(_ amount: Double)
func showLoading()
func hideLoading()
}
protocol PaymentMethodsPresenterProtocol: class {
func viewDidLoad()
func didSelectPaymentMethod(method: PaymentMethod)
}
protocol PaymentMethodsRouterProtocol: class {
func goToQRPayment(transaction: Transaction, request: PaymentRequest)
func goToCTTPayment(transaction: Transaction, request: PaymentRequest)
func goToSposPayment(transaction: Transaction, request: PaymentRequest)
func goToCashPayment(transaction: Transaction, request: PaymentRequest)
}
| [
-1
] |
db31c291adc9e580fda6aa70ff2c3dbaca10673f | 0234807782d1106f40d602e6bfff97349a9d2a7b | /japan_terebi-iOS/japan_terebi-iOSTests/japan_terebi_iOSTests.swift | b7a8048bfc7397c73e06a7561a80abccfc8da439 | [
"MIT"
] | permissive | Animenosekai/japan_terebi-iOS | 726209f650b6073109c30e366363a4094ac60952 | 952dd03be1b031b9d9f72c058484a17157390e57 | refs/heads/master | 2022-09-26T02:46:14.973348 | 2020-06-04T11:02:53 | 2020-06-04T11:02:53 | 269,336,140 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 947 | swift | //
// japan_terebi_iOSTests.swift
// japan_terebi-iOSTests
//
// Created by Anime no Sekai on 09/04/2020.
// Copyright © 2020 Anime no Sekai. All rights reserved.
//
import XCTest
@testable import japan_terebi_iOS
class japan_terebi_iOSTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| [
333828,
43014,
358410,
354316,
313357,
360462,
399373,
317467,
145435,
229413,
204840,
315432,
325674,
344107,
315434,
102445,
155694,
176175,
233517,
124975,
346162,
129076,
241716,
229430,
243767,
163896,
180280,
358456,
241720,
288828,
436285,
376894,
124984,
288833,
288834,
436292,
403525,
352326,
225351,
315465,
436301,
338001,
196691,
338003,
280661,
329814,
307289,
385116,
237663,
254048,
315487,
356447,
280675,
280677,
43110,
319591,
321637,
436329,
194666,
221290,
438377,
260207,
432240,
204916,
233589,
266357,
131191,
215164,
215166,
422019,
280712,
415881,
104587,
235662,
241808,
381073,
196760,
284826,
426138,
346271,
436383,
362659,
299174,
333991,
333996,
239793,
377009,
125109,
405687,
182456,
180408,
295098,
258239,
379071,
389313,
299203,
149703,
299209,
346314,
372941,
266449,
321745,
139479,
229597,
194782,
301279,
311519,
317664,
280802,
379106,
387296,
346346,
205035,
307435,
321772,
438511,
381172,
436470,
327929,
243962,
344313,
184575,
149760,
375039,
411906,
125183,
125188,
147717,
368905,
125193,
325905,
254226,
272658,
368916,
262421,
125203,
325912,
381208,
377114,
125208,
151839,
237856,
237857,
233762,
211235,
217380,
432421,
211238,
125217,
151847,
338218,
325931,
311597,
358703,
321840,
98610,
332083,
379186,
332085,
358709,
180535,
336183,
332089,
125235,
125240,
321860,
332101,
438596,
323913,
348492,
323920,
344401,
366930,
377169,
348500,
368981,
155990,
289110,
368984,
168281,
215385,
332123,
332127,
98657,
383332,
242023,
383336,
270701,
160110,
242033,
270706,
354676,
139640,
291192,
317820,
211326,
436608,
362881,
240002,
436611,
311685,
225670,
317831,
106888,
340357,
242058,
385417,
311691,
373134,
385422,
108944,
252308,
190871,
213403,
149916,
121245,
242078,
420253,
141728,
315810,
315811,
381347,
289189,
108972,
272813,
340398,
385454,
377264,
311727,
342450,
338356,
436661,
293303,
311738,
33211,
293310,
336320,
311745,
127427,
416197,
254406,
188871,
324039,
129483,
342476,
373197,
289232,
328152,
256477,
287198,
160225,
342498,
358882,
340453,
334309,
391655,
432618,
375276,
319981,
291311,
254456,
377338,
377343,
174593,
254465,
240131,
291333,
340490,
139792,
420369,
342548,
303636,
258581,
393751,
416286,
377376,
207393,
375333,
377386,
244269,
197167,
375343,
385588,
289332,
234036,
375351,
174648,
338489,
338490,
244281,
315960,
242237,
348732,
70209,
301638,
115270,
70215,
293448,
55881,
309830,
348742,
348749,
381517,
385615,
426576,
369235,
416341,
297560,
332378,
201308,
416351,
139872,
436832,
436834,
268899,
111208,
39530,
184940,
373358,
420463,
346737,
389745,
313971,
139892,
346740,
420471,
287352,
344696,
209530,
244347,
373375,
152195,
311941,
336518,
348806,
311945,
369289,
330379,
344715,
311949,
287374,
326287,
375440,
316049,
311954,
334481,
117396,
111253,
316053,
346772,
230040,
264856,
111258,
111259,
271000,
289434,
303771,
205471,
318106,
318107,
342682,
139939,
344738,
377500,
176808,
205487,
303793,
318130,
299699,
293556,
336564,
383667,
314040,
287417,
39614,
287422,
377539,
422596,
422599,
291530,
225995,
363211,
164560,
242386,
385747,
361176,
418520,
422617,
287452,
318173,
363230,
264928,
422626,
375526,
246503,
234217,
330474,
342762,
293612,
342763,
289518,
299759,
369385,
377489,
312052,
154359,
172792,
344827,
221948,
432893,
205568,
162561,
291585,
295682,
430849,
291592,
197386,
383754,
62220,
117517,
434957,
322319,
322316,
422673,
377497,
430865,
166676,
291604,
310036,
197399,
207640,
422680,
426774,
426775,
326429,
293664,
326433,
197411,
400166,
289576,
293672,
295724,
152365,
197422,
353070,
164656,
295729,
422703,
191283,
318252,
422709,
152374,
197431,
273207,
375609,
160571,
289598,
160575,
336702,
430910,
342847,
160580,
252741,
381773,
201551,
293711,
353109,
377686,
184973,
244568,
230234,
189275,
244570,
435039,
295776,
242529,
349026,
357218,
303972,
385893,
342887,
308076,
242541,
330609,
246641,
246643,
207732,
295798,
361337,
269178,
177019,
185211,
308092,
398206,
400252,
291712,
158593,
254850,
359298,
260996,
359299,
113542,
369538,
381829,
240518,
316298,
392074,
295824,
224145,
349072,
355217,
256922,
289690,
318364,
390045,
310176,
185250,
310178,
420773,
185254,
289703,
293800,
140204,
236461,
363438,
347055,
377772,
304051,
326581,
373687,
326587,
230332,
377790,
289727,
273344,
330689,
353215,
363458,
379844,
213957,
19399,
326601,
345033,
373706,
316364,
359381,
386006,
418776,
433115,
248796,
343005,
50143,
347103,
123881,
326635,
359406,
187374,
383983,
347123,
316405,
240630,
271350,
201720,
127992,
295927,
349175,
328700,
318461,
293886,
257024,
328706,
330754,
320516,
293893,
295942,
357379,
386056,
410627,
353290,
330763,
377869,
433165,
384016,
238610,
308243,
418837,
140310,
433174,
320536,
252958,
330788,
369701,
357414,
248872,
238639,
300084,
312373,
203830,
359478,
238651,
308287,
336960,
214086,
377926,
218186,
314448,
341073,
339030,
439384,
156765,
304222,
392290,
253029,
257125,
300135,
316520,
273515,
173166,
357486,
144496,
351344,
404593,
316526,
377972,
285814,
291959,
300150,
300151,
363641,
160891,
363644,
300158,
377983,
392318,
150657,
248961,
384131,
349316,
402565,
349318,
302216,
330888,
386189,
373903,
169104,
177296,
326804,
363669,
238743,
119962,
300187,
300188,
339100,
351390,
199839,
380061,
429214,
265379,
300201,
249002,
253099,
253100,
238765,
3246,
300202,
306346,
238769,
318639,
402613,
367799,
421048,
373945,
113850,
294074,
339130,
322749,
302274,
367810,
259268,
265412,
353479,
402634,
283852,
259280,
290000,
333011,
316627,
189653,
419029,
148696,
296153,
304351,
195808,
298208,
310497,
298212,
298213,
222440,
330984,
328940,
298221,
298228,
302325,
234742,
386294,
128251,
386301,
261377,
320770,
386306,
437505,
322824,
439562,
292107,
328971,
414990,
353551,
251153,
177428,
349462,
257305,
320796,
222494,
253216,
339234,
372009,
412971,
353584,
261425,
351537,
382258,
345396,
300343,
386359,
378172,
286013,
306494,
382269,
216386,
345415,
312648,
337225,
304456,
230729,
146762,
224586,
177484,
294218,
259406,
234831,
238927,
294219,
331090,
353616,
406861,
318805,
314710,
372054,
425304,
159066,
374109,
314720,
378209,
314726,
163175,
333160,
386412,
380271,
327024,
296307,
249204,
249205,
116084,
208244,
316787,
290173,
306559,
314751,
318848,
337281,
148867,
357762,
253317,
298374,
314758,
314760,
142729,
296329,
368011,
384393,
388487,
314766,
296335,
318864,
112017,
234898,
9619,
259475,
275859,
318868,
370071,
212375,
357786,
212382,
290207,
314783,
251298,
310692,
208293,
314789,
333220,
314791,
396711,
245161,
396712,
316842,
374191,
286129,
380337,
173491,
286132,
150965,
304564,
353719,
380338,
228795,
425405,
302531,
380357,
339398,
361927,
300489,
425418,
306639,
413137,
23092,
210390,
210391,
210393,
286172,
144867,
271843,
429542,
245223,
191981,
296433,
251378,
308723,
321009,
343542,
300536,
286202,
359930,
302590,
372227,
323080,
329225,
253451,
296461,
359950,
259599,
304656,
329232,
146964,
308756,
370197,
175639,
253463,
374296,
388632,
374299,
308764,
396827,
134686,
431649,
286244,
245287,
402985,
394794,
245292,
169518,
347694,
431663,
288309,
312889,
194110,
349763,
196164,
124485,
265798,
288327,
218696,
292425,
128587,
265804,
333388,
396882,
128599,
179801,
44635,
239198,
343647,
333408,
396895,
99938,
300644,
323172,
310889,
415338,
243307,
312940,
54893,
204397,
138863,
188016,
222832,
325231,
224883,
314998,
333430,
247416,
323196,
325245,
337534,
337535,
339584,
263809,
294529,
194180,
288392,
229001,
415375,
188048,
239250,
419478,
425626,
302754,
153251,
298661,
40614,
300714,
210603,
224946,
337591,
384695,
110268,
415420,
224958,
327358,
333503,
274115,
259781,
333509,
306890,
403148,
212685,
333517,
9936,
9937,
241361,
302802,
333520,
272085,
345814,
370388,
384720,
333523,
345821,
321247,
298720,
321249,
325346,
333542,
153319,
325352,
345833,
345834,
212716,
212717,
360177,
67315,
173814,
325371,
124669,
288512,
319233,
339715,
288516,
360195,
339720,
243472,
372496,
323346,
321302,
345879,
366360,
398869,
325404,
286494,
321310,
255776,
339745,
257830,
247590,
421672,
362283,
378668,
399147,
431916,
300848,
409394,
296755,
319288,
259899,
319292,
360252,
325439,
345919,
436031,
403267,
153415,
360264,
345929,
341836,
415567,
325457,
317269,
18262,
216918,
241495,
341847,
362327,
346779,
350044,
128862,
245599,
345951,
362337,
376669,
345955,
425825,
296806,
292712,
425833,
423789,
214895,
313199,
362352,
325492,
276341,
417654,
341879,
241528,
317304,
333688,
112509,
55167,
182144,
325503,
305026,
339841,
188292,
333701,
243591,
315273,
315274,
325515,
325518,
372626,
380821,
329622,
294807,
337815,
333722,
376732,
118685,
298909,
311199,
319392,
350109,
292771,
436131,
294823,
415655,
436137,
333735,
327596,
362417,
323507,
124852,
243637,
290745,
294843,
188348,
362431,
237504,
294850,
274371,
384964,
214984,
151497,
321480,
362443,
344013,
212942,
301008,
153554,
24532,
372701,
329695,
436191,
372043,
292836,
292837,
298980,
313319,
317415,
380908,
436205,
327661,
311281,
311282,
325619,
432116,
333817,
292858,
415741,
352917
] |
924eddf9c0885a93f2aa2f6eff03dc833d8e82a9 | 5536570f87289243ff4ec3f82766d2ea91bd68cb | /20201203/20201203.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift | b870a2d168e8a803f3dd64c20bd0ddc7d49de49d | [
"MIT"
] | permissive | akio0911/til | 2b3a1ac1a109cac5e6f4724e0161af0777cc2d85 | fcc264b48905d3e883fc7ba839ac4eb437c877fb | refs/heads/master | 2021-04-26T16:47:10.518937 | 2021-01-16T13:04:39 | 2021-01-16T13:04:39 | 58,748,611 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 359 | swift | import UIKit
func group(_ a: [Int]) -> [[Int]] {
if a.isEmpty {
return []
} else {
let x = a.first!
let xs = a.dropFirst()
let eq: (Int) -> Bool = { $0 == x }
let r1 = [[x] + xs.prefix(while: eq)]
let r2 = group([Int](xs.drop(while: eq)))
return r1 + r2
}
}
group([1,1,1,2,2,3,4,4,4,1,1])
| [
-1
] |
a7a6b48d17697f226f661a7c2adde0d8f1d0e73e | bc8298781decca14b1efde8f49eec7e0592d56bd | /SuperService/SuperService/TaskhistoryModel.swift | f5c34aef8babc71dfb95b675e31f2afdad549ca7 | [] | no_license | zkjs/SuperService-iOS | 72eea8758e18eef863bf8e7784dd7739ab5c358d | 5c60b0ac370e49be1e9e1e67ea4ccb2f3d05fd8d | refs/heads/master | 2021-01-19T17:36:46.057909 | 2016-08-09T11:53:44 | 2016-08-09T11:53:44 | 42,839,076 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 806 | swift | //
// TaskhistoryModel.swift
// SuperService
//
// Created by AlexBang on 16/6/23.
// Copyright © 2016年 ZKJS. All rights reserved.
//
import UIKit
class TaskhistoryModel {
var username:String?
var userimage:String?
var actiondesc:String?
var createtime:String?
var statuscode:ActionType
var actionname:String?
var userid:String?
init(json:JSON) {
username = json["username"].string ?? ""
userimage = json["userimage"].string ?? ""
actiondesc = json["actiondesc"].string ?? ""
createtime = json["createtime"].string ?? ""
if let a = json["actioncode"].int,status = ActionType(rawValue:a) {
statuscode = status
} else {
statuscode = .Unknown
}
actionname = json["actionname"].string ?? ""
userid = json["userid"].string ?? ""
}
}
| [
-1
] |
ef8212e5bbd37130d523871c720b9ad6563749eb | 66812f905157f31618957ad7f9c01b8da7777cf0 | /Sources/StripeKit/API/Routes/CardholderRoutes.swift | 83704db4481fcc5d2f131cdb3389eb3874edbdcf | [
"MIT"
] | permissive | VCGMobile/Kitura-StripeKit | 3162a6f57c61986e2dcfff8dd358fb987a5a1fdb | d2f15c96fbf6f3ba06fe7538c83b7aff739b0925 | refs/heads/master | 2020-06-12T13:02:27.572910 | 2019-07-02T19:02:14 | 2019-07-02T19:02:14 | 194,307,816 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 10,377 | swift | //
// CardholderRoutes.swift
// Stripe
//
// Created by Andrew Edwards on 5/29/19.
//
import NIO
import NIOHTTP1
public protocol CardholderRoutes {
/// Creates a new Issuing Cardholder object that can be issued cards.
///
/// - Parameters:
/// - billing: The cardholder’s billing address.
/// - name: The cardholder’s name. This will be printed on cards issued to them.
/// - type: The type of cardholder. Possible values are `individual` or `business_entity`.
/// - authorizationControls: Spending rules that give you control over how your cardholders can make charges. Refer to our [authorizations](https://stripe.com/docs/issuing/authorizations) documentation for more details. This will be unset if you POST an empty value.
/// - email: The cardholder’s email address.
/// - isDefault: Specifies whether to set this as the default cardholder.
/// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`.
/// - phoneNumber: The cardholder’s phone number. This will be transformed to E.164 if it is not provided in that format already.
/// - status: Specifies whether to permit authorizations on this cardholder’s cards. Possible values are `active` or `inactive`.
/// - Returns: A `StripeCardholder`.
/// - Throws: A `StripeError`.
func create(billing: [String: Any],
name: String,
type: StripeCardholderType,
authorizationControls: [String: Any]?,
email: String?,
isDefault: Bool?,
metadata: [String: String]?,
phoneNumber: String?,
status: StripeCardholderStatus?) throws -> EventLoopFuture<StripeCardholder>
/// Retrieves an Issuing Cardholder object.
///
/// - Parameter cardholder: The identifier of the cardholder to be retrieved.
/// - Returns: A `StripeCardholder`.
/// - Throws: A `StripeError`.
func retrieve(cardholder: String) throws -> EventLoopFuture<StripeCardholder>
/// Updates the specified Issuing Cardholder object by setting the values of the parameters passed. Any parameters not provided will be left unchanged.
///
/// - Parameters:
/// - cardholder: The ID of the cardholder to update.
/// - authorizationControls: Spending rules that give you control over how your cardholders can make charges. Refer to our [authorizations](https://stripe.com/docs/issuing/authorizations) documentation for more details. This will be unset if you POST an empty value.
/// - billing: The cardholder’s billing address.
/// - email: The cardholder’s email address.
/// - isDefault: Specifies whether to set this as the default cardholder.
/// - metadata: Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format. Individual keys can be unset by posting an empty value to them. All keys can be unset by posting an empty value to `metadata`.
/// - phoneNumber: The cardholder’s phone number. This will be transformed to E.164 if it is not provided in that format already.
/// - status: Specifies whether to permit authorizations on this cardholder’s cards. Possible values are `active` or `inactive`.
/// - Returns: A `StripeCardholder`.
/// - Throws: A `StripeError`.
func update(cardholder: String,
authorizationControls: [String: Any]?,
billing: [String: Any]?,
email: String?,
isDefault: Bool?,
metadata: [String: String]?,
phoneNumber: String?,
status: StripeCardholderStatus?) throws -> EventLoopFuture<StripeCardholder>
/// Returns a list of Issuing Cardholder objects. The objects are sorted in descending order by creation date, with the most recently created object appearing first.
///
/// - Parameter filter: A dictionary that will be used for the query parameters. [See More →](https://stripe.com/docs/api/issuing/cardholders/list).
/// - Returns: A `StripeAuthorizationList`.
/// - Throws: A `StripeError`.
func listAll(filter: [String: Any]?) throws -> EventLoopFuture<StripeAuthorizationList>
var headers: HTTPHeaders { get set }
}
extension CardholderRoutes {
func create(billing: [String: Any],
name: String,
type: StripeCardholderType,
authorizationControls: [String: Any]? = nil,
email: String? = nil,
isDefault: Bool? = nil,
metadata: [String: String]? = nil,
phoneNumber: String? = nil,
status: StripeCardholderStatus? = nil) throws -> EventLoopFuture<StripeCardholder> {
return try create(billing: billing,
name: name,
type: type,
authorizationControls: authorizationControls,
email: email,
isDefault: isDefault,
metadata: metadata,
phoneNumber: phoneNumber,
status: status)
}
func retrieve(cardholder: String) throws -> EventLoopFuture<StripeCardholder> {
return try retrieve(cardholder: cardholder)
}
func update(cardholder: String,
authorizationControls: [String: Any]? = nil,
billing: [String: Any]? = nil,
email: String? = nil,
isDefault: Bool? = nil,
metadata: [String: String]? = nil,
phoneNumber: String? = nil,
status: StripeCardholderStatus? = nil) throws -> EventLoopFuture<StripeCardholder> {
return try update(cardholder: cardholder,
authorizationControls: authorizationControls,
billing: billing,
email: email,
isDefault: isDefault,
metadata: metadata,
phoneNumber: phoneNumber,
status: status)
}
func listAll(filter: [String: Any]? = nil) throws -> EventLoopFuture<StripeAuthorizationList> {
return try listAll(filter: filter)
}
}
public struct StripeCardholderRoutes: CardholderRoutes {
private let apiHandler: StripeAPIHandler
public var headers: HTTPHeaders = [:]
init(apiHandler: StripeAPIHandler) {
self.apiHandler = apiHandler
}
public func create(billing: [String: Any],
name: String,
type: StripeCardholderType,
authorizationControls: [String: Any]?,
email: String?,
isDefault: Bool?,
metadata: [String: String]?,
phoneNumber: String?,
status: StripeCardholderStatus?) throws -> EventLoopFuture<StripeCardholder> {
var body: [String: Any] = ["name": name,
"type": type.rawValue]
billing.forEach { body["billing[\($0)]"] = $1 }
if let authorizationControls = authorizationControls {
authorizationControls.forEach { body["authorization_controls[\($0)]"] = $1 }
}
if let email = email {
body["email"] = email
}
if let isDefault = isDefault {
body["is_default"] = isDefault
}
if let metadata = metadata {
metadata.forEach { body["metadata[\($0)]"] = $1 }
}
if let phoneNumber = phoneNumber {
body["phone_number"] = phoneNumber
}
if let status = status {
body["status"] = status.rawValue
}
return try apiHandler.send(method: .POST, path: StripeAPIEndpoint.cardholder.endpoint, body: .string(body.queryParameters), headers: headers)
}
public func retrieve(cardholder: String) throws -> EventLoopFuture<StripeCardholder> {
return try apiHandler.send(method: .GET, path: StripeAPIEndpoint.cardholders(cardholder).endpoint, headers: headers)
}
public func update(cardholder: String,
authorizationControls: [String: Any]?,
billing: [String: Any]?,
email: String?,
isDefault: Bool?,
metadata: [String: String]?,
phoneNumber: String?,
status: StripeCardholderStatus?) throws -> EventLoopFuture<StripeCardholder> {
var body: [String: Any] = [:]
if let authorizationControls = authorizationControls {
authorizationControls.forEach { body["authorization_controls[\($0)]"] = $1 }
}
if let billing = billing {
billing.forEach { body["billing[\($0)]"] = $1 }
}
if let email = email {
body["email"] = email
}
if let isDefault = isDefault {
body["is_default"] = isDefault
}
if let metadata = metadata {
metadata.forEach { body["metadata[\($0)]"] = $1 }
}
if let phoneNumber = phoneNumber {
body["phone_number"] = phoneNumber
}
if let status = status {
body["status"] = status.rawValue
}
return try apiHandler.send(method: .POST, path: StripeAPIEndpoint.cardholders(cardholder).endpoint, body: .string(body.queryParameters), headers: headers)
}
public func listAll(filter: [String : Any]?) throws -> EventLoopFuture<StripeAuthorizationList> {
var queryParams = ""
if let filter = filter {
queryParams = filter.queryParameters
}
return try apiHandler.send(method: .GET, path: StripeAPIEndpoint.cardholder.endpoint, query: queryParams, headers: headers)
}
}
| [
-1
] |
ddd694e34178d8641c04f12906c0c427a80715b1 | 866327780013f67f22f0ef235e9d274cfa87c4b7 | /Yelp/SwitchCell.swift | 82ee20c97caba664ac2bf537cff27f77c663d16e | [
"Apache-2.0"
] | permissive | chaitanyatejagolla/Yelp | b198b963620eaad0a1e7a5f8b77117091e56c71c | 485693c2d9cfda2254d6885eeb67e19b578f5863 | refs/heads/master | 2021-01-19T09:24:09.361715 | 2017-04-11T01:07:19 | 2017-04-11T01:07:19 | 87,753,893 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,017 | swift | //
// SwitchCell.swift
// Yelp
//
// Created by Golla, Chaitanya Teja on 4/8/17.
// Copyright © 2017 Timothy Lee. All rights reserved.
//
import UIKit
@objc protocol SwitchCellDelegate {
@objc optional func switchCell(switchCell: SwitchCell, didChangeValue value: Bool)
}
class SwitchCell: UITableViewCell {
@IBOutlet weak var switchLabel: UILabel!
@IBOutlet weak var onSwitch: UISwitch!
weak var delegate: SwitchCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
onSwitch.addTarget(self, action: #selector(SwitchCell.switchValueChanged), for: UIControlEvents.valueChanged)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func switchValueChanged() {
print("switch value changed")
delegate?.switchCell?(switchCell: self, didChangeValue: onSwitch.isOn)
}
}
| [
276845,
277079
] |
b6eda0a3e52048c5fbbf8f9d68ebb62fffc5d106 | b1a20730dd9e3e9c0bb58b778a902e114dce6d8b | /Timber/FileLogger.swift | fda998888eb71ab8bd5a674ea5c8b02b96a6c550 | [
"MIT"
] | permissive | MadeByHecho/Timber | bd33a059cbb3e8136fccae4dbba45d389d062986 | 620070b984f97c6fde03e7e588a29aedc693466f | refs/heads/master | 2021-01-23T18:58:01.667579 | 2015-07-26T09:38:45 | 2015-07-26T09:38:45 | 35,535,849 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 8,951 | swift | //
// FileLogger.swift
// Timber
//
// Created by Scott Petit on 9/7/14.
// Copyright (c) 2014 Scott Petit. All rights reserved.
//
import Foundation
public struct FileLogger: LoggerType {
public init() {
FileManager.purgeOldFiles()
FileManager.purgeOldestFilesGreaterThanCount(5)
print("Timber - Saving logs to \(FileManager.currentLogFilePath())")
}
//MARK: Logger
public var messageFormatter: MessageFormatterType = MessageFormatter()
public func logMessage(message: LogMessage) {
let currentData = FileManager.currentLogFileData()
let mutableData = NSMutableData(data: currentData)
var messageToLog = messageFormatter.formatLogMessage(message)
messageToLog += "\n"
if let dataToAppend = messageToLog.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
mutableData.appendData(dataToAppend)
}
if let filePath = FileManager.currentLogFilePath() {
mutableData.writeToFile(filePath, atomically: false)
}
}
}
struct FileManager {
static let userDefaultsKey = "com.Timber.currentLogFile"
static let maximumLogFileSize = 1024 * 1024 // 1 mb
static let maximumFileExsitenceInterval: NSTimeInterval = 60 * 60 * 24 * 180 // 180 days
static func currentLogFilePath() -> String? {
if let path: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(userDefaultsKey) {
return path as? String
} else {
return createNewLogFilePath()
}
}
static func shouldCreateNewLogFileForData(data: NSData) -> Bool {
return data.length > maximumLogFileSize
}
static func createNewLogFilePath() -> String? {
if let logsDirectory = defaultLogsDirectory() {
let newLogFilePath = logsDirectory.stringByAppendingPathComponent(newLogFileName())
NSUserDefaults.standardUserDefaults().setObject(newLogFilePath, forKey: userDefaultsKey)
NSUserDefaults.standardUserDefaults().synchronize()
return newLogFilePath
}
return nil
}
static func newLogFileName() -> String {
let appName = applicationName()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'_'HH'-'mm'"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let formattedDate = dateFormatter.stringFromDate(NSDate())
let newLogFileName = "\(appName)_\(formattedDate).log"
return newLogFileName
}
static func applicationName() -> String {
let processName = NSProcessInfo.processInfo().processName
if processName.characters.count > 0 {
return processName
} else {
return "<UnnamedApp>"
}
}
static func defaultLogsDirectory() -> String? {
// Update how we get file URLs per Apple Technical Note https://developer.apple.com/library/ios/technotes/tn2406/_index.html
let cachesDirectoryPathURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).last as NSURL!
if cachesDirectoryPathURL.fileURL {
if let cachesDirectoryPath = cachesDirectoryPathURL.path {
let logsDirectory = cachesDirectoryPath.stringByAppendingPathComponent("Timber")
if !NSFileManager.defaultManager().fileExistsAtPath(logsDirectory) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(logsDirectory, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
}
return logsDirectory
}
}
return nil
}
static func currentLogFileData() -> NSData {
if let filePath = currentLogFilePath() {
if let data = NSData(contentsOfFile: filePath) {
if shouldCreateNewLogFileForData(data) {
createNewLogFilePath()
}
return data
}
}
return NSData()
}
static func purgeOldFiles() {
if let logsDirectory = defaultLogsDirectory() {
TrashMan.takeOutFilesInDirectory(logsDirectory, withExtension: "log", notModifiedSince: NSDate(timeIntervalSinceNow: -maximumFileExsitenceInterval))
}
}
static func purgeOldestFilesGreaterThanCount(count: Int) {
if let logsDirectory = defaultLogsDirectory() {
TrashMan.takeOutOldestFilesInDirectory(logsDirectory, greaterThanCount: count)
}
}
}
struct TrashMan {
static func takeOutFilesInDirectory(directoryPath: String, notModifiedSince minimumModifiedDate: NSDate) {
takeOutFilesInDirectory(directoryPath, withExtension: nil, notModifiedSince: minimumModifiedDate)
}
static func takeOutFilesInDirectory(directoryPath: String, withExtension fileExtension: String?, notModifiedSince minimumModifiedDate: NSDate) {
let fileURL = NSURL(fileURLWithPath: directoryPath, isDirectory: true)
let fileManager = NSFileManager.defaultManager()
let contents: [AnyObject]?
do {
contents = try fileManager.contentsOfDirectoryAtURL(fileURL, includingPropertiesForKeys: [NSURLAttributeModificationDateKey], options: .SkipsHiddenFiles)
} catch _ {
contents = nil
}
if let files = contents as? [NSURL] {
for file in files {
var fileDate: AnyObject?
let haveDate: Bool
do {
try file.getResourceValue(&fileDate, forKey: NSURLAttributeModificationDateKey)
haveDate = true
} catch _ {
haveDate = false
}
if !haveDate {
continue
}
if fileDate?.timeIntervalSince1970 >= minimumModifiedDate.timeIntervalSince1970 {
continue
}
if fileExtension != nil {
if file.pathExtension != fileExtension! {
continue
}
}
do {
try fileManager.removeItemAtURL(file)
} catch _ {
}
}
}
}
static func takeOutOldestFilesInDirectory(directoryPath: String, greaterThanCount count: Int) {
let directoryURL = NSURL(fileURLWithPath: directoryPath, isDirectory: true)
let contents: [AnyObject]?
do {
contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [NSURLCreationDateKey], options: .SkipsHiddenFiles)
} catch _ {
contents = nil
}
if let files = contents as? [NSURL] {
if count >= files.count {
return
}
let sortedFiles = files.sort({ (firstFile: NSURL, secondFile: NSURL) -> Bool in
var firstFileObject: AnyObject?
let haveFirstDate: Bool
do {
try firstFile.getResourceValue(&firstFileObject, forKey: NSURLCreationDateKey)
haveFirstDate = true
} catch {
haveFirstDate = false
}
if !haveFirstDate {
return false
}
var secondFileObject: AnyObject?
let haveSecondDate: Bool
do {
try secondFile.getResourceValue(&secondFileObject, forKey: NSURLCreationDateKey)
haveSecondDate = true
} catch {
haveSecondDate = false
}
if !haveSecondDate {
return true
}
let firstFileDate = firstFileObject as! NSDate
let secondFileDate = secondFileObject as! NSDate
let comparisonResult = firstFileDate.compare(secondFileDate)
return comparisonResult == NSComparisonResult.OrderedDescending
})
for (index, fileURL) in sortedFiles.enumerate() {
if index >= count {
do {
try NSFileManager.defaultManager().removeItemAtURL(fileURL)
} catch {
}
}
}
}
}
}
| [
-1
] |
f2be367732251b55d1661147f874e11870776b47 | b1e322e7450095feda54b877b7c9a2479c4956c3 | /DemoApp/AppDelegate.swift | b344fad003af9b9f7e7379cb2c84c3bd418c759f | [] | no_license | varshasingh15/Swift-Data-Display-Demo | cb4711d4d94665210faacc1834a7668b9f19fc0c | b9a38645d63a49fa93f32711a65c1064d1d67789 | refs/heads/master | 2020-03-24T16:37:11.563410 | 2018-07-30T05:50:49 | 2018-07-30T05:50:49 | 142,830,366 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,921 | swift | //
// AppDelegate.swift
// DemoApp
//
// Created by Varsha Singh on 7/11/18.
// Copyright © 2018 DemoApp. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
private let viewControllerIdentifier = "courseListViewController" //listViewController identifier
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
// ViewController is added to root of the window
if let window = window {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = storyboard.instantiateViewController(withIdentifier: viewControllerIdentifier)
navigationController = UINavigationController(rootViewController: initialViewController)
window.rootViewController = navigationController
window.makeKeyAndVisible()
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| [
294924,
294950,
229415,
229417,
327722,
237613,
229422,
229426,
229428,
311349,
286774,
286776,
319544,
286778,
229432,
286791,
237640,
286797,
237646,
311375,
163920,
196692,
319573,
311383,
319590,
311400,
303212,
131192,
237693,
303230,
327814,
303241,
303244,
319633,
286873,
286876,
311469,
32944,
327862,
286906,
327866,
286910,
286916,
286924,
286926,
131281,
295133,
319716,
237807,
303345,
286962,
303347,
229622,
327930,
237826,
319751,
286987,
319757,
286999,
319770,
287003,
287006,
287009,
287012,
287014,
287016,
287019,
311598,
287023,
311601,
295220,
319809,
319810,
319814,
311623,
311628,
319822,
287054,
229717,
196963,
196969,
139638,
213367,
106872,
311683,
319879,
311693,
311719,
139689,
311728,
311741,
319938,
319945,
188895,
172512,
287202,
172520,
319978,
172526,
311791,
172529,
319989,
172534,
180727,
311804,
287230,
303617,
172550,
303623,
172552,
320007,
172558,
303632,
303637,
172572,
172577,
295459,
172581,
295461,
172591,
172598,
172607,
172609,
172612,
172614,
213575,
172618,
303690,
33357,
303696,
172634,
172644,
311911,
172656,
352880,
295538,
172660,
287349,
295553,
172675,
295557,
311942,
352905,
311946,
311951,
287377,
172691,
287381,
311957,
221850,
287386,
230045,
172702,
303773,
172705,
287394,
172707,
303780,
287398,
205479,
295595,
189102,
172721,
287409,
66227,
303797,
189114,
287419,
328381,
287423,
328384,
172737,
172748,
287436,
172751,
287440,
295633,
172755,
303827,
287450,
303835,
189149,
303838,
312035,
295654,
230128,
312048,
312050,
205564,
230146,
328453,
230154,
312077,
295695,
230169,
295707,
328476,
295710,
230175,
295720,
303914,
230202,
312124,
328508,
222018,
148302,
287569,
303959,
230237,
230241,
303976,
336744,
303985,
303987,
303991,
303997,
295806,
295808,
295813,
304005,
320391,
304007,
304009,
304011,
304013,
295822,
189329,
295825,
304019,
279445,
304027,
304042,
213931,
230327,
304055,
287675,
230334,
304063,
304065,
213954,
156612,
197580,
312272,
304090,
320481,
304106,
320490,
312302,
328687,
320496,
304114,
295928,
295945,
230413,
320528,
140312,
295961,
238620,
304164,
304170,
304175,
238641,
238652,
238655,
238658,
336964,
320584,
238666,
296021,
402518,
336987,
230497,
296036,
296040,
361576,
205931,
296044,
312432,
337018,
304258,
205968,
296084,
238745,
304285,
238756,
222377,
337067,
238766,
230576,
238770,
304311,
230592,
312518,
230600,
230607,
148690,
320727,
304354,
296163,
320740,
304360,
320748,
304370,
320771,
312585,
296202,
296205,
230674,
320786,
230677,
296213,
296215,
320792,
230681,
230689,
173350,
312622,
312630,
296253,
296255,
312639,
230727,
238919,
296264,
320840,
296267,
296271,
230739,
312663,
222556,
337244,
312676,
230760,
148843,
230763,
230768,
296305,
312692,
230773,
304505,
304506,
181631,
148865,
312711,
296331,
288140,
288144,
304533,
173488,
288176,
312755,
312759,
288185,
222652,
312766,
173507,
222665,
230860,
312783,
288208,
222676,
239070,
296435,
288250,
296446,
321022,
402942,
296450,
230916,
230919,
230923,
304651,
304653,
230940,
222752,
296486,
296488,
157229,
230961,
157236,
288320,
288325,
124489,
288338,
288344,
239194,
239202,
312938,
116354,
288408,
321195,
296622,
321200,
337585,
296634,
296637,
206536,
313044,
321239,
313052,
288478,
313055,
321252,
288494,
321266,
288499,
288502,
288510,
124671,
198405,
313093,
198416,
321304,
321311,
313121,
313123,
304932,
321316,
321336,
296767,
288576,
345921,
304968,
173907,
313171,
313176,
321381,
296809,
296812,
313201,
305028,
124817,
239510,
124827,
214944,
321458,
296883,
124853,
214966,
296890,
288700,
296894,
190403,
296900,
337862,
165831,
296921,
239586,
124913,
165876,
239612,
313340,
288764,
239617,
313347,
288773,
313358,
305176,
313371,
305191,
223273,
313386,
124978,
215090,
124980,
288824,
288826,
321595,
313406,
288831,
288836,
215123,
288859,
280669,
149599,
149601,
321634,
149603,
149618,
215154,
313458,
313464,
329850,
321659,
288895,
321670,
215175,
313498,
100520,
288947,
321717,
313548,
321740,
313557,
338147,
125171,
280825,
125187,
125191,
125207,
125209,
321817,
125218,
321842,
223539,
125239,
289087,
305480,
305485,
305489,
354653,
313700,
280940,
190832,
313720,
313731,
199051,
240011,
289166,
240017,
297363,
240021,
297365,
297372,
297377,
289186,
297391,
289201,
240052,
289207,
289210,
305594,
289218,
166378,
305647,
174580,
240124,
305662,
305664,
240129,
305666,
305668,
223749,
240132,
223752,
150025,
338440,
322074,
150066,
158266,
289342,
322115,
199262,
338528,
199273,
19053,
158317,
313973,
297594,
158347,
314003,
117398,
289436,
174754,
330404,
289448,
174764,
314029,
314033,
240309,
314045,
314047,
314051,
297671,
158409,
289493,
289513,
289522,
289532,
322303,
322310,
322314,
322318,
322341,
215850,
289601,
240458,
240468,
322393,
224110,
207733,
207737,
158596,
183172,
338823,
322440,
314249,
183184,
289687,
240535,
289694,
289696,
289700,
289724,
289762,
183277,
322550,
134142,
322563,
314372,
175134,
322599,
322610,
314421,
314427,
314433,
314441,
322642,
314456,
314461,
248995,
306341,
306344,
306347,
322734,
306354,
199877,
289991,
306377,
289997,
290008,
363742,
298216,
330988,
216303,
257302,
363802,
199976,
199978,
298292,
298294,
216376,
380226,
298306,
224587,
216404,
306517,
150870,
314714,
314718,
314723,
150890,
306539,
314732,
314736,
290161,
306549,
298358,
314743,
306552,
290171,
314747,
306555,
290174,
224641,
298372,
314756,
224647,
298377,
314763,
298381,
314768,
224657,
306581,
314773,
314779,
314785,
314793,
241068,
241070,
241072,
150966,
306618,
323015,
306635,
306640,
290263,
290270,
290275,
339431,
191985,
290291,
241142,
191992,
290298,
290302,
290305,
306694,
257550,
290325,
241175,
290328,
290332,
241181,
290344,
306731,
290349,
290356,
224849,
306778,
314979,
298598,
323176,
224875,
241260,
323181,
290445,
298651,
282269,
323229,
298655,
323231,
306856,
323266,
241362,
306904,
52959,
241380,
323318,
241412,
323345,
323349,
315167,
315169,
315174,
323367,
241448,
315176,
241450,
306991,
315184,
323376,
315190,
241464,
159545,
298811,
118593,
307009,
413506,
307012,
298822,
315211,
307027,
315221,
315223,
241496,
241498,
307035,
307040,
110433,
241509,
110438,
298860,
110445,
315249,
315253,
315255,
339838,
315267,
315269,
241544,
241546,
241548,
298896,
298898,
241556,
298901,
241560,
241563,
241565,
241567,
241569,
241574,
298922,
241581,
241583,
323504,
241586,
290739,
241588,
241590,
241592,
241598,
290751,
241600,
241605,
151495,
241610,
298975,
241632,
298984,
241643,
298988,
241646,
241649,
241652,
290807,
299003,
241661,
299006,
315396,
241669,
315397,
290835,
241693,
102438,
290877,
315463,
315466,
192596,
176213,
307290,
217179,
315482,
192605,
315483,
233567,
299105,
200801,
217188,
299109,
307303,
356457,
45163,
307307,
315502,
192624,
307314,
299126,
233591,
299136,
307329,
307338,
233613,
241813,
307352,
299164,
299167,
315552,
315557,
184486,
307370,
307372,
307374,
307376,
323763,
184503,
307385,
307388,
307390,
299200,
307394,
299204,
307396,
184518,
307399,
323784,
233679,
307409,
307411,
299225,
233701,
307432,
291104,
315701,
332086,
307510,
151864,
307515,
307518,
151874,
323917,
233808,
323921,
315733,
323926,
233815,
315739,
299357,
242018,
242024,
299373,
250231,
242043,
315771,
299391,
291202,
242057,
291212,
299405,
291222,
315801,
242075,
61855,
291231,
291238,
291241,
127403,
127405,
291247,
299440,
127407,
127413,
127417,
291260,
127421,
127424,
299457,
127429,
127434,
315856,
315860,
127447,
299481,
176605,
242143,
127457,
291299,
127463,
291305,
127466,
176620,
127469,
127474,
291314,
291317,
127480,
135672,
291323,
233979,
127485,
291330,
127494,
127497,
233994,
135689,
127500,
233998,
127506,
234003,
234006,
127511,
152087,
135707,
135710,
242206,
242208,
291361,
242220,
291378,
152118,
234038,
234041,
315961,
70213,
111193,
242275,
299620,
242279,
135805,
135808,
316051,
316054,
135834,
373404,
135839,
299684,
135844,
242343,
242345,
373421,
135870,
135873,
135876,
135879,
299720,
299723,
299726,
299740,
201444,
299750,
234219,
316151,
242431,
299778,
234246,
291601,
234258,
242452,
201496,
234264,
234266,
234272,
152355,
299814,
185138,
234296,
160572,
316233,
316235,
234319,
185173,
201557,
308063,
234336,
242530,
349027,
234344,
152435,
177011,
234356,
291711,
291714,
201603,
291716,
234373,
324490,
324504,
308123,
234396,
324508,
291742,
291747,
291748,
234405,
291750,
324518,
324520,
324522,
291756,
324527,
291760,
201650,
324531,
324536,
291773,
242623,
324544,
234434,
324546,
324548,
291788,
234464,
168935,
324585,
316400,
234481,
316403,
234485,
234487,
316416,
308231,
300054,
316439,
234520,
234526,
300066,
300069,
234540,
234546,
300085,
234553,
316479,
234561,
316483,
160835,
234563,
308291,
316491,
234572,
300108,
234574,
300115,
234593,
234597,
300133,
300139,
234610,
316530,
300148,
144506,
234620,
275594,
177293,
234640,
308373,
324757,
234647,
234650,
308379,
300189,
324766,
119967,
324768,
242852,
300197,
234667,
316596,
308414,
234687,
300223,
300226,
308418,
234692,
300229,
308420,
308422,
316610,
300234,
300238,
283854,
300241,
316625,
300243,
300245,
316630,
300248,
300253,
300256,
300258,
300260,
300263,
300265,
300267,
300270,
300272,
300278,
275703,
316663,
300284,
275710,
300287,
292097,
300289,
300292,
275719,
234760,
177419,
300299,
242957,
300301,
275725,
349464,
300344,
243003,
300357,
316758,
357722,
316766,
292192,
316768,
292197,
316774,
243046,
218473,
136562,
316803,
316806,
316811,
316814,
300433,
234899,
300436,
357783,
316824,
316826,
300448,
144810,
144814,
144820,
374196,
292279,
144826,
144830,
144832,
144837,
144839,
144841,
144844,
144847,
144852,
144855,
103899,
300507,
333280,
218597,
292329,
300523,
300527,
308720,
292338,
316917,
292343,
300537,
316933,
316947,
308757,
308762,
284194,
284196,
235045,
284199,
284204,
284206,
284209,
284211,
194101,
284213,
316983,
194103,
284215,
308790,
284218,
292414,
284223,
284226,
284228,
292421,
284231,
284234,
317004,
284238,
284241,
194130,
284243,
300628,
284245,
292433,
284247,
284249,
292452,
292454,
292458,
292461,
284272,
284274,
284278,
292470,
292473,
284283,
284286,
292479,
284288,
292481,
284290,
325250,
284292,
292485,
284297,
317066,
284299,
317068,
284301,
284303,
284306,
284308,
284312,
276122,
284314,
284316,
284320,
284322,
284327,
284329,
317098,
284331,
284333,
284335,
284337,
284339,
300726,
284343,
284346,
284350,
358080,
284354,
358083,
284358,
358089,
284362,
284365,
284368,
284370,
358098,
284372,
317138,
358114,
358116,
358119,
325353,
358122,
358126,
358128,
358133,
358135,
358138,
300795,
358140,
358142,
358146,
317189,
317191,
300816,
300819,
317207,
300830,
300832,
325408,
317221,
358183,
243504,
300850,
325436,
358206,
366406,
292681,
153417,
358224,
317271,
292700,
317279,
292715,
292721,
300915,
284533,
292729,
317306,
292734,
325512,
317332,
358292,
350106,
358312,
317353,
292784,
358326,
358330,
301011,
301013,
292823,
358360,
301017,
301015,
292828,
292839,
292843,
178161,
325624,
317435,
317446,
317456,
317458,
178195,
243733,
243740,
317468,
317472,
325666,
243751,
243762,
309298,
325685,
325689,
235579,
325692,
235581,
178238,
325700,
292934,
243785,
350293,
350295,
309337,
350302,
350304,
178273,
309346,
194660,
350308,
309350,
309348,
292968,
309352,
350313,
309354,
301163,
350316,
301167,
350321,
350325,
252022,
350328,
292985,
350332,
292989,
301185,
292993,
350339,
317573,
350342,
350345,
350349,
317584,
325777,
350354,
350357,
350359,
350362,
350366,
350375,
350379,
350381,
350383,
350385,
350387,
350389,
350395,
350397,
350399,
350402,
301252,
350406,
301258,
309455,
301272,
194780,
309468,
309471,
301283,
317672,
317674,
325867,
309494,
325910,
309530,
342298,
276766,
317729,
211241,
325937,
325943,
211260,
235853,
235858,
391523,
293227,
293232,
186744,
211324,
317833,
317853,
317858,
342434,
317864,
235955,
293304,
293307,
293314,
309707,
317910,
293336,
235996,
317917,
293343,
358880,
293346,
293364,
301562,
293370,
317951,
309764,
301575,
293387,
342541,
113167,
309779,
317971,
309781,
293417,
227882,
309804,
236082,
23094,
301636,
318020,
301639,
301643,
309844,
309849,
326244,
318055,
121458,
309885,
309888,
301706,
318092,
326285,
334476,
318108,
318110,
137889,
383658,
318128,
293555,
318144,
137946,
113378,
342760,
56043,
56059,
310015,
310029,
293659,
326430,
285474,
293666,
318248,
318253,
293677,
301876,
293685,
301880,
301884,
293696,
162643,
310100,
301911,
301921,
236397,
162671,
326514,
236408,
416639,
113538,
310147,
416648,
301972,
424853,
310179,
293798,
293802,
236460,
293817,
293820,
203715,
326603,
318442,
326638,
318450,
293876,
302073,
121850,
293882,
302075,
293899,
293908,
302105,
293917,
293939,
318516,
310336,
293956,
293960,
203857,
293971,
310355,
310359,
236632,
138332,
310374,
310376,
277608,
318573,
367737,
302205,
392326,
294026,
162964,
384148,
187542,
302231,
285849,
302233,
285852,
302237,
285854,
285856,
302241,
302248,
64682,
294063,
302258,
318651,
318657,
244930,
130244,
302282,
310476,
302285,
302288,
310481,
302290,
302292,
302294,
310486,
302296,
310498,
302315,
294132,
138485,
204026,
204031,
64768,
310531,
285999,
318773,
318776,
286010,
417086,
302403,
294221,
294223,
326991,
294246,
327015,
310632,
327017,
351594,
351607,
310648,
310651,
310657,
351619,
294276,
310659,
253320,
310665,
318858,
310672,
310689,
130468,
228776,
310703,
310710,
310712,
302526,
228799,
302534,
310727,
245191,
302541,
302543,
310737,
310749,
310755,
310764,
310772,
327156,
40440,
212472,
40443,
286203,
40448,
286214,
302603,
302614,
302621,
286240,
146977,
187939,
40484,
40486,
286246,
294440,
40488,
294439,
294443,
40491,
294445,
286248,
310831,
40499,
40502,
212538,
40507,
40511,
40513,
327240,
40521,
40525,
40527,
212560,
400976,
40529,
40533,
40537,
40539,
40541,
40544,
40548,
40550,
40552,
40554,
310892,
40557,
40560,
294521,
343679,
294537,
302740,
179870,
327333,
229030,
319153,
302781,
302789,
294599,
294601,
302793,
343757,
212690,
319187,
286425,
319194,
294625,
294634,
302838,
319226,
286460,
302852,
302854,
294664,
311048,
319243,
311053,
302862,
319251,
294682,
188199,
294701,
319290,
229192,
302925,
188247,
188252,
237409,
294785,
237470,
319390,
40865,
319394,
311209,
343983,
294844,
294847,
294876,
294879,
237555,
311283,
237562
] |
34870c2bd74e8b81e28d84c45966c92c69785dd8 | b8e116cb514cbc801f9fcd1b50b5e89caa38b7e1 | /RandomTrip/City.swift | c207c76a61e1a05b0e678abf99b2abf7ed64a75b | [] | no_license | Rammaryu/RandomTrip | 029ada121dce09db505d2e580106b05451f4288d | ec3ebf983940b0ea4ef8ceeec2e7305eaf816a19 | refs/heads/master | 2020-09-20T04:19:45.137510 | 2019-11-27T07:57:03 | 2019-11-27T07:57:03 | 224,375,064 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 689 | swift | //
// City.swift
// RandomTrip
//
// Created by Ishii Yugo on 2018/08/28.
// Copyright © 2018年 yugo. All rights reserved.
//
import Foundation
import SwiftyJSON
class City{
var id:String = ""
var name:String = ""
}
//struct City {
// var cityNumber: Int
// var cityArray:[Dictionary<String,String>]
// let prefectureName: String
// let cityName: String
//
// init(json: JSON) {
// self.cityArray = json["data"].arrayValue
// self.cityNumber = self.cityArray.count
// self.cityName = json["data"][arc4random_uniform(UInt32(cityNumber))+1]["name"].stringValue
// // self.prefectureName = json[]
//
// }
//
//}
| [
-1
] |
3e342c775ac7ca5af470e226c079806895ce32cf | bc30d69fb215d0ab13d6743202b44720d85b0cd5 | /BestAppStore/Components/ScreenshotImageView.swift | 2ecf155d703b2bd435f924a6fef4603f93c39d44 | [] | no_license | PasiBergman/BestAppStore | ecbd714b3a4a301ffc7f28f862e80fff1cbcec2f | 99828695f0a59c647c8868024dcb2ca77b6f49bc | refs/heads/master | 2022-04-09T06:22:09.361228 | 2020-03-28T22:30:22 | 2020-03-28T22:30:22 | 250,185,231 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 886 | swift | //
// ScreenShotImageView.swift
// BestAppStore
//
// Created by Pasi Bergman on 25.3.2020.
// Copyright © 2020 Pasi Bergman. All rights reserved.
//
import UIKit
class ScreenshotImageView: UIImageView {
init(cornerRadius: CGFloat) {
super.init(frame: .zero)
self.clipsToBounds = true
self.layer.cornerRadius = cornerRadius
self.backgroundColor = .clear
self.layer.borderWidth = 0.5
self.layer.borderColor = UIColor.init(white: 0.5, alpha: 1).cgColor
self.contentMode = .scaleAspectFill
}
func setScreenshot(screenshotUrl: String) {
guard let url = URL(string: screenshotUrl) else {
layer.borderWidth = 0
return
}
self.sd_setImage(with: url)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| [
-1
] |
65b2d91403ae900c423b0a25535c4759374eb7e1 | 30910c40c108185bfa003f77e63f382dfe5a9ebb | /ios/Familylada/Familylada/SettingsView.swift | 077b050019b8b64e3201c3fea7ef5e760de0d347 | [] | no_license | kpuc00/sem4-smart-mobile-group-repo | 370131a01880a3a437d504e7619cf715a46c1e81 | f0645a41ce1f9f5742045ffacf6e3d2be2e0f233 | refs/heads/master | 2023-06-04T02:13:24.780227 | 2021-06-23T23:36:05 | 2021-06-23T23:36:05 | 369,576,598 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,081 | swift | //
// SettingsView.swift
// Familylada
//
// Created by Kristiyan Strahilov on 12.05.21.
//
import SwiftUI
struct SettingsView: View {
@State private var enableLocation = false
@State private var enableStorage = true
@State private var enableDarkMode = false
var skins = ["Skin 1", "Skin 2", "Skin 3"]
@State private var selectedSkin = 0
var body: some View {
Form {
Section(header: Text("Permissions")) {
Toggle("Location", isOn: $enableLocation)
Toggle("Storage", isOn: $enableStorage)
}
Section(header: Text("Appearance")) {
Picker("Change skin", selection: $selectedSkin) {
ForEach(0..<skins.count) {
Text(skins[$0])
}
}
Toggle("Dark mode", isOn: $enableDarkMode)
}
}
.navigationTitle("Settings")
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
| [
-1
] |
e6063faf535bad364c491d41e9c922660803702a | a68504a799e39c315e670d0bf88d7cf98deeccda | /WeatherForecast/Model/CityInfo.swift | 6320189098e3e824b5af675a76661ba5399d3be0 | [] | no_license | DmytroSemeniuk/WeatherForecast | 58985d5aa86f0b7f9abd61511bf6b5264455db36 | 312df0c9d0845dc4f68a4652c07e00dc0bc39878 | refs/heads/master | 2020-11-29T20:00:29.625607 | 2019-12-26T05:42:04 | 2019-12-26T05:42:04 | 230,203,460 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 340 | swift | //
// CityInfo.swift
// WeatherForecast
//
// Created by Dmitry Sem on 9/13/19.
// Copyright © 2019 Dmitry Sem. All rights reserved.
//
import UIKit
class CityInfo: Codable {
let id: Int?
let name: String?
let coord: Coord?
let country: String?
}
// MARK: - Coord
struct Coord: Codable {
let lat, lon: Double?
}
| [
-1
] |
2c2f1150458eaa18b73c09ddead0111b07a61ff0 | 04a983b5df7c0c64d45c428164af3c637e2e3af2 | /Sources/HAP/Base/Predefined/Enums/Enums.TargetHeatingCoolingState.swift | c0922725d6c13e85d91bdcd2cf5cf8e0794528e0 | [
"MIT"
] | permissive | Bouke/HAP | e4264b3394b737ea0fa300c58f6deca4fff3ef7a | 51e3505a34eb842f7491fda48bb4ef873b16b68c | refs/heads/master | 2023-08-05T05:00:06.059443 | 2022-12-31T09:55:04 | 2022-12-31T09:55:04 | 62,937,440 | 372 | 76 | MIT | 2023-01-06T15:22:45 | 2016-07-09T07:10:37 | Swift | UTF-8 | Swift | false | false | 189 | swift | public extension Enums {
enum TargetHeatingCoolingState: UInt8, CharacteristicValueType {
case off = 0
case heat = 1
case cool = 2
case auto = 3
}
}
| [
-1
] |
5b806cf7ea0c5c0279e928c79e42f0873aa4ba01 | e531ddc037ccda2ef1804a631bfa027a83e2c85a | /RandomPictures/AppDelegate.swift | 0e29f85c09aa982c2ac0dbf16e36f898562b457c | [] | no_license | headstream12/Random-Pictures | d08348b99f901034dd3d5e97f01ec76d4059f046 | 3765b029b7cc001702341b269f9344d8f84edd5c | refs/heads/main | 2022-12-12T05:33:24.032799 | 2020-09-09T13:13:11 | 2020-09-09T13:13:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 614 | swift | //
// AppDelegate.swift
// RandomPictures
//
// Created by Igor Kryukov on 26/08/2020.
// Copyright © 2020 User. All rights reserved.
//
import Alamofire
import UIKit
import Foundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = TabBarController()
window?.makeKeyAndVisible()
return true
}
}
| [
142193,
357421,
381094,
247647
] |
cda8f38567ea249ce7a8b4be8d202f08b2dea7f4 | b9980d154e26849abebe18051e619fb31ea3b2c3 | /Views/TableViewCells/Product/ProductCategoryCell.swift | 7ccf81448f416137fe51da0dab1eb1757c78112b | [
"MIT"
] | permissive | AgrinobleAGN/Agrinoble-Mobile-App-iOS | acd1040e8b0e3bb4c2bf1efeae6a26462f775de9 | 9c28c53b8f3b74afcf5ba1e280c2f7ac36de2403 | refs/heads/main | 2023-07-18T12:29:44.182492 | 2021-09-02T09:29:13 | 2021-09-02T09:29:13 | 402,361,069 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 191 | swift |
import UIKit
import WoWonderTimelineSDK
class ProductCategoryCell: UICollectionViewCell {
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var categoryView: DesignView!
}
| [
-1
] |
9dd78dd67adc91314561442368543998df775331 | df723222c8286310c2a816d99c18a63fe15e0348 | /Service/Controllers/ServiceDetailsViewController/Cells/ScheduleTableViewCell.swift | 0bae0f617c5f17fb3081d92f2e38417afb9b2d2f | [] | no_license | Ferdens/example | 12a7fcc11f08508fc1e373b278c098638422d076 | bec1707772f2e8c47e1ed8450e01a873450e7327 | refs/heads/master | 2020-06-10T12:37:42.612445 | 2019-06-25T06:17:53 | 2019-06-25T06:17:53 | 193,646,154 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,439 | swift | //
// DetailTableViewCell.swift
// Service
//
// Created by anton Shepetuha on 03.08.2018.
// Copyright © 2018 Anton. All rights reserved.
//
import Foundation
import UIKit
class ScheduleTableViewCell: UITableViewCell {
let titleLabel = UILabel()
let dataLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.backgroundColor = .clear
self.contentView.backgroundColor = .clear
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.textColor = AppColors.serviceSteel
self.contentView.addSubview(titleLabel)
titleLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 6).isActive = true
titleLabel.setContentHuggingPriority(UILayoutPriority.defaultLow + 2, for: .horizontal)
let titleLabelWidhtConstraint = titleLabel.widthAnchor.constraint(lessThanOrEqualTo: self.contentView.widthAnchor, multiplier: 0.4)
titleLabelWidhtConstraint.isActive = true
titleLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 6).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0).isActive = true
dataLabel.translatesAutoresizingMaskIntoConstraints = false
dataLabel.font = UIFont.systemFont(ofSize: 16)
dataLabel.textColor = AppColors.serviceSteel
self.contentView.addSubview(dataLabel)
dataLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -6).isActive = true
dataLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 6).isActive = true
dataLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0).isActive = true
let dataLabelWidthConstraint = dataLabel.widthAnchor.constraint(lessThanOrEqualTo: self.contentView.widthAnchor, multiplier: 0.5)
dataLabelWidthConstraint.isActive = true
let separatorView = UIView()
separatorView.translatesAutoresizingMaskIntoConstraints = false
separatorView.backgroundColor = AppColors.serviceSteel
separatorView.setContentHuggingPriority(UILayoutPriority.defaultLow, for: .horizontal)
if let prioroty = UILayoutConstraintAxis(rawValue: 749) {
separatorView.contentCompressionResistancePriority(for: prioroty)
}
self.contentView.addSubview(separatorView)
separatorView.centerYAnchor.constraint(equalTo: dataLabel.centerYAnchor).isActive = true
separatorView.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 4).isActive = true
separatorView.trailingAnchor.constraint(equalTo: dataLabel.leadingAnchor, constant: -4).isActive = true
separatorView.heightAnchor.constraint(equalToConstant: 2).isActive = true
self.contentView.sendSubview(toBack: separatorView)
}
override func prepareForReuse() {
super.prepareForReuse()
dataLabel.text = ""
titleLabel.text = ""
dataLabel.textColor = AppColors.serviceSteel
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| [
-1
] |
cf939449b4241e81dafadcb2cd9747e1ae23b014 | 79c48a2e901c9de0250a3ed307e42f628843f822 | /LiangCangZangChunyu/LiangCangZangChunyu/ViewController.swift | 04215264c78f37f92ee06d4bda69cd2a93ec4ab1 | [] | no_license | ZCYTSL/GuLi | 7eced69a46f951bfd9399f23109c05c86d512d42 | 2c72e9b51ccb8a7416bbb04fdb2c87360eda9e29 | refs/heads/master | 2020-07-03T18:10:37.924417 | 2016-09-25T03:05:50 | 2016-09-25T03:05:50 | 67,112,517 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 512 | swift | //
// ViewController.swift
// LiangCangZangChunyu
//
// Created by qianfeng on 16/8/8.
// Copyright © 2016年 qianfeng. 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.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| [
307212,
278543,
292915,
286775,
237624,
288827,
290875,
286786,
284740,
243786,
286796,
237655,
307288,
200802,
356460,
307311,
278657,
276612,
280710,
303242,
311437,
278675,
307353,
299165,
278693,
100521,
307379,
184504,
280760,
280770,
227523,
280772,
280775,
280777,
313550,
276686,
229585,
307410,
280808,
280810,
286963,
280821,
286965,
280826,
280832,
276736,
309506,
278791,
287007,
282917,
233767,
307516,
289088,
311624,
287055,
289120,
289121,
227688,
313706,
299374,
199024,
276849,
313733,
227740,
285087,
289187,
305582,
285103,
278968,
293308,
278973,
289224,
281078,
233980,
287231,
279041,
279046,
215562,
281107,
279064,
236057,
281118,
289318,
309807,
279096,
234043,
277057,
129604,
301637,
158285,
281202,
277108,
287350,
117399,
228000,
287399,
277171,
285377,
285378,
287437,
299727,
226009,
277224,
199402,
234223,
312049,
289524,
226038,
234232,
226055,
299786,
295696,
295699,
281373,
228127,
281380,
234279,
283433,
293682,
289596,
283453,
279360,
289600,
293700,
283461,
295766,
308064,
293742,
162672,
291709,
303998,
183173,
304008,
324491,
304012,
234380,
304015,
277406,
234402,
291755,
324528,
230323,
234423,
277432,
281530,
295874,
299973,
234465,
168936,
183278,
277487,
293874,
293875,
293888,
277508,
277512,
275466,
234511,
304174,
300086,
234551,
300089,
238653,
293961,
300107,
300116,
281703,
296042,
164974,
312433,
300149,
189557,
234619,
285837,
226447,
234641,
349332,
302235,
285855,
234665,
283839,
277696,
228551,
279751,
279754,
230604,
298189,
302286,
230608,
189655,
302295,
363743,
298211,
228585,
120054,
292102,
312586,
296216,
130346,
300358,
238920,
234829,
230737,
230745,
306540,
300400,
333179,
290175,
275842,
224643,
298375,
300432,
226705,
310673,
304531,
304536,
304540,
304550,
304551,
144811,
286126,
277935,
282035,
292277,
296374,
130487,
144822,
292280,
306633,
288205,
286158,
280015,
310734,
286162,
163289,
286175,
286189,
282095,
308721,
296436,
288251,
290299,
290303,
286234,
294433,
282145,
284197,
296487,
296489,
226878,
288321,
226887,
284235,
288331,
226896,
212561,
284242,
292435,
228945,
300629,
276054,
212573,
40545,
284261,
306791,
286314,
284275,
314996,
294518,
276087,
284287,
284289,
284298,
278157,
282262,
280219,
284315,
284317,
282270,
282275,
198315,
313007,
302767,
284336,
284341,
286390,
300727,
276150,
282301,
302788,
282311,
284361,
239310,
282320,
239314,
282329,
282338,
284391,
282346,
358127,
282357,
288501,
358139,
282365,
286462,
282368,
358147,
282377,
300817,
282389,
282393,
329499,
315170,
282403,
282411,
159541,
282426,
288579,
307029,
241499,
188253,
296811,
315250,
284534,
292730,
294812,
284576,
284580,
284586,
276396,
282548,
296901,
165832,
301012,
301016,
292824,
294889,
231405,
298989,
227315,
237556
] |
89c82f8292fa13639cec4309d4eefc1476f0a6c4 | 39cfcfaf45747944873d4d3f548bde130a5addaa | /Sources/Intramodular/Navigation/NavigationBarConfigurator.swift | 102aefad033b74e0caa056d10cc63dc49906659a | [
"MIT"
] | permissive | jwandrews/SwiftUIX | 2ac779a0809b0954d786b9c328656602bfa9f93b | 806822b13d2cc9482f7bfc25ba98159914d53b68 | refs/heads/master | 2023-09-04T22:35:21.527692 | 2023-08-16T07:47:26 | 2023-08-16T07:47:26 | 262,190,490 | 0 | 0 | MIT | 2020-05-08T00:44:01 | 2020-05-08T00:44:00 | null | UTF-8 | Swift | false | false | 16,856 | swift | //
// Copyright (c) Vatsal Manot
//
import Swift
import SwiftUI
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
@usableFromInline
struct NavigationBarConfigurator<Leading: View, Center: View, Trailing: View, LargeTrailing: View>: UIViewControllerRepresentable {
@usableFromInline
class UIViewControllerType: UIViewController {
weak var navigationBarLargeTitleView: UIView? = nil
var navigationBarLargeTitleTrailingItemHostingController: UIHostingController<LargeTrailing>? = nil
var leading: Leading?
var center: Center?
var trailing: Trailing?
var largeTrailing: LargeTrailing?
var largeTrailingAlignment: VerticalAlignment?
var displayMode: NavigationBarItem.TitleDisplayMode?
var hasMovedToParentOnce: Bool = false
var isVisible: Bool = false
override func willMove(toParent parent: UIViewController?) {
if !hasMovedToParentOnce {
updateNavigationBar(viewController: parent?.navigationController?.visibleViewController)
hasMovedToParentOnce = true
}
super.willMove(toParent: parent)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateNavigationBar(viewController: parent?.navigationController?.visibleViewController)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isVisible = true
updateNavigationBar(viewController: parent?.navigationController?.visibleViewController)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationBarLargeTitleTrailingItemHostingController?.view.removeFromSuperview()
navigationBarLargeTitleTrailingItemHostingController = nil
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
isVisible = false
updateNavigationBar(viewController: parent?.navigationController?.visibleViewController)
}
func updateNavigationBar(viewController: UIViewController?) {
guard let parent = viewController else {
return
}
#if os(iOS) || targetEnvironment(macCatalyst)
if let displayMode = displayMode {
switch displayMode {
case .automatic:
parent.navigationItem.largeTitleDisplayMode = .automatic
case .inline:
parent.navigationItem.largeTitleDisplayMode = .never
case .large:
parent.navigationItem.largeTitleDisplayMode = .always
@unknown default:
parent.navigationItem.largeTitleDisplayMode = .automatic
}
}
#endif
if let leading = leading, !(leading is EmptyView) {
if parent.navigationItem.leftBarButtonItem == nil {
parent.navigationItem.leftBarButtonItem = .init(customView: UIHostingView(rootView: leading))
} else if let view = parent.navigationItem.leftBarButtonItem?.customView as? UIHostingView<Leading> {
view.rootView = leading
} else {
parent.navigationItem.leftBarButtonItem?.customView = UIHostingView(rootView: leading)
}
} else {
parent.navigationItem.leftBarButtonItem = nil
}
if let center = center, !(center is EmptyView) {
if let view = parent.navigationItem.titleView as? UIHostingView<Center> {
view.rootView = center
} else {
parent.navigationItem.titleView = UIHostingView(rootView: center)
}
} else {
parent.navigationItem.titleView = nil
}
if let trailing = trailing, !(trailing is EmptyView) {
if parent.navigationItem.rightBarButtonItem == nil {
parent.navigationItem.rightBarButtonItem = .init(customView: UIHostingView(rootView: trailing))
} else if let view = parent.navigationItem.rightBarButtonItem?.customView as? UIHostingView<Trailing> {
view.rootView = trailing
} else {
parent.navigationItem.rightBarButtonItem?.customView = UIHostingView(rootView: trailing)
}
} else {
parent.navigationItem.rightBarButtonItem = nil
}
parent.navigationItem.leftBarButtonItem?.customView?.sizeToFit()
parent.navigationItem.titleView?.sizeToFit()
parent.navigationItem.rightBarButtonItem?.customView?.sizeToFit()
if let largeTrailing = largeTrailing, !(largeTrailing is EmptyView), isVisible {
guard let navigationBar = self.navigationController?.navigationBar else {
return
}
guard let _UINavigationBarLargeTitleView = NSClassFromString("_" + "UINavigationBar" + "LargeTitleView") else {
return
}
for subview in navigationBar.subviews {
if subview.isKind(of: _UINavigationBarLargeTitleView.self) {
navigationBarLargeTitleView = subview
}
}
if let navigationBarLargeTitleView = navigationBarLargeTitleView {
if let hostingController = navigationBarLargeTitleTrailingItemHostingController, hostingController.view.superview == navigationBarLargeTitleView {
hostingController.rootView = largeTrailing
} else {
let hostingController = UIHostingController(rootView: largeTrailing)
hostingController.view.backgroundColor = .clear
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
navigationBarLargeTitleView.addSubview(hostingController.view)
NSLayoutConstraint.activate([
hostingController.view.trailingAnchor.constraint(
equalTo: navigationBarLargeTitleView.layoutMarginsGuide.trailingAnchor
)
])
switch (largeTrailingAlignment ?? .center) {
case .top:
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(
equalTo: navigationBarLargeTitleView.topAnchor
)
])
case .center:
NSLayoutConstraint.activate([
hostingController.view.centerYAnchor.constraint(
equalTo: navigationBarLargeTitleView.centerYAnchor
)
])
case .bottom:
NSLayoutConstraint.activate([
hostingController.view.bottomAnchor.constraint(
equalTo: navigationBarLargeTitleView.bottomAnchor
)
])
default:
NSLayoutConstraint.activate([
hostingController.view.centerYAnchor.constraint(
equalTo: navigationBarLargeTitleView.centerYAnchor
)
])
}
self.navigationBarLargeTitleTrailingItemHostingController = hostingController
}
}
} else {
self.navigationBarLargeTitleTrailingItemHostingController?.view.removeFromSuperview()
self.navigationBarLargeTitleTrailingItemHostingController = nil
}
}
}
let leading: Leading
let center: Center
let trailing: Trailing
let largeTrailing: LargeTrailing
let largeTrailingAlignment: VerticalAlignment?
let displayMode: NavigationBarItem.TitleDisplayMode?
@usableFromInline
init(
leading: Leading,
center: Center,
trailing: Trailing,
largeTrailing: LargeTrailing,
largeTrailingAlignment: VerticalAlignment? = nil,
displayMode: NavigationBarItem.TitleDisplayMode?
) {
self.leading = leading
self.center = center
self.trailing = trailing
self.largeTrailing = largeTrailing
self.largeTrailingAlignment = largeTrailingAlignment
self.displayMode = displayMode
}
@usableFromInline
func makeUIViewController(context: Context) -> UIViewControllerType {
.init()
}
@usableFromInline
func updateUIViewController(_ viewController: UIViewControllerType, context: Context) {
viewController.displayMode = displayMode
viewController.leading = leading
viewController.center = center
viewController.trailing = trailing
viewController.largeTrailing = largeTrailing
viewController.largeTrailingAlignment = largeTrailingAlignment
viewController.updateNavigationBar(viewController: viewController.navigationController?.topViewController)
}
@usableFromInline
static func dismantleUIViewController(_ uiViewController: UIViewControllerType, coordinator: Coordinator) {
uiViewController.largeTrailingAlignment = nil
uiViewController.updateNavigationBar(viewController: uiViewController.navigationController?.topViewController)
}
}
extension View {
@inlinable
public func navigationBarItems<Leading: View, Center: View, Trailing: View>(
leading: Leading,
center: Center,
trailing: Trailing,
displayMode: NavigationBarItem.TitleDisplayMode? = .automatic
) -> some View {
background(
NavigationBarConfigurator(
leading: leading,
center: center,
trailing: trailing,
largeTrailing: EmptyView(),
displayMode: displayMode
)
)
}
@inlinable
public func navigationBarItems<Leading: View, Center: View>(
leading: Leading,
center: Center,
displayMode: NavigationBarItem.TitleDisplayMode = .automatic
) -> some View {
navigationBarItems(
leading: leading,
center: center,
trailing: EmptyView(),
displayMode: displayMode
)
}
@inlinable
public func navigationBarTitleView<V: View>(
_ center: V,
displayMode: NavigationBarItem.TitleDisplayMode
) -> some View {
navigationBarItems(
leading: EmptyView(),
center: center,
trailing: EmptyView(),
displayMode: displayMode
)
}
@inlinable
public func navigationBarTitleView<V: View>(
_ center: V
) -> some View {
withEnvironmentValue(\.presenter) { presenter in
navigationBarItems(
leading: EmptyView(),
center: center.environment(\.presenter, presenter),
trailing: EmptyView(),
displayMode: .automatic
)
}
}
@inlinable
public func navigationBarItems<Center: View, Trailing: View>(
center: Center,
trailing: Trailing,
displayMode: NavigationBarItem.TitleDisplayMode = .automatic
) -> some View {
navigationBarItems(
leading: EmptyView(),
center: center,
trailing: trailing,
displayMode: displayMode
)
}
}
extension View {
@available(tvOS, unavailable)
public func navigationBarLargeTitleItems<Trailing: View>(
trailing: Trailing,
alignment: VerticalAlignment? = nil,
displayMode: NavigationBarItem.TitleDisplayMode? = .large
) -> some View {
background(
NavigationBarConfigurator(
leading: EmptyView(),
center: EmptyView(),
trailing: EmptyView(),
largeTrailing: trailing.font(.largeTitle),
largeTrailingAlignment: alignment,
displayMode: displayMode
)
)
}
/// Set a custom view for the navigation bar's large view mode.
@available(tvOS, unavailable)
public func navigationBarLargeTitle<Content: View>(
@ViewBuilder content: () -> Content
) -> some View {
background {
_NavigationBarLargeTitleViewConfigurator(content: content())
.frameZeroClipped()
.accessibility(hidden: true)
}
}
}
// MARK: - Auxiliary
struct _NavigationBarLargeTitleViewConfigurator<Content: View>: UIViewControllerRepresentable {
private let content: Content
init(content: Content) {
self.content = content
}
func makeUIViewController(context: Context) -> UIViewControllerType {
UIViewControllerType(content: content)
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
uiViewController.contentHostingController.mainView = content
}
class UIViewControllerType: UIViewController {
let contentHostingController: CocoaHostingController<Content>
private weak var navigationBarLargeTitleView: UIView?
init(content: Content) {
self.contentHostingController = .init(mainView: content)
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError()
}
override func viewWillAppear(_ animated: Bool) {
guard contentHostingController.view.superview == nil else {
return
}
guard
let navigationBar = navigationController?.navigationBar,
let navigationBarLargeTitleViewClass = NSClassFromString("_UINavigationBarLargeTitleView"),
let navigationBarLargeTitleView = navigationBar.subviews.first(where: { $0.isKind(of: navigationBarLargeTitleViewClass.self) })
else {
return
}
self.navigationBarLargeTitleView = navigationBarLargeTitleView
navigationBarLargeTitleView.subviews.forEach {
$0.isHidden = true
}
contentHostingController.view.backgroundColor = .clear
contentHostingController.view.clipsToBounds = true
contentHostingController.view.translatesAutoresizingMaskIntoConstraints = false
navigationBar.addSubview(contentHostingController.view)
NSLayoutConstraint.activate([
contentHostingController.view.leadingAnchor.constraint(equalTo: navigationBarLargeTitleView.leadingAnchor),
contentHostingController.view.trailingAnchor.constraint(equalTo: navigationBarLargeTitleView.trailingAnchor),
contentHostingController.view.bottomAnchor.constraint(equalTo: navigationBarLargeTitleView.bottomAnchor),
contentHostingController.view.heightAnchor.constraint(equalTo: navigationBarLargeTitleView.heightAnchor)
])
contentHostingController.view.setNeedsLayout()
contentHostingController.view.layoutSubviews()
super.viewWillAppear(animated)
}
deinit {
contentHostingController.view.removeFromSuperview()
navigationBarLargeTitleView?.subviews.forEach {
$0.isHidden = false
}
}
}
}
#endif
| [
-1
] |
a5cd7718205867c31be251f41bf0fe76400566f1 | 4bfadac15f4a527585edaf63cc7df20bb462a9ff | /LeetCode.playground/Pages/41. First Missing Positive.xcplaygroundpage/Contents.swift | 6759f51fefa8d32b065b493d99fb6efaee09742f | [
"MIT"
] | permissive | BugenZhao/LeetCode.playground | 40f28c00b4b9cdb2f6ef3da6049029e805fdf0e0 | c237693c2b50e55833a3e4a734510509ea1caa01 | refs/heads/master | 2023-03-21T13:52:41.830430 | 2021-03-15T14:49:20 | 2021-03-15T14:49:20 | 256,462,277 | 18 | 3 | null | null | null | null | UTF-8 | Swift | false | false | 740 | swift | let tags: [Tag] = [.array, .marked]
class Solution {
func firstMissingPositive(_ nums: [Int]) -> Int {
if nums.isEmpty { return 1 }
var nums = nums
for i in nums.indices {
//: note that the answer must be in `{1,2,...,count,count+1}`
//: swap every number to its right place (`[1,2,3,...]`)
while 1...nums.count ~= nums[i], nums[i] != nums[nums[i] - 1] {
nums.swapAt(i, nums[i] - 1)
}
}
print(nums)
return (nums.indices.first { nums[$0] != $0 + 1 } ?? nums.endIndex) + 1 //: find the first incorrect one
}
}
let f = Solution().firstMissingPositive
f([1, 2, 0])
f([0, 1, 2])
f([1, 2, 3])
f([5, 6, 7])
f([1, 1])
f([])
| [
-1
] |
3b7820cade32839f9312d68d6f5f4a6922ef9c06 | 58a8f196944f20a04162c8d16d1882a1435560e7 | /CategoryTheory.playground/Pages/Chapter3.xcplaygroundpage/Contents.swift | 336b52ad6b3b74a78ab4721d43ad3a5a07dba6d5 | [] | no_license | turnipdabeets/CategoryTheoryForProgrammers | 2287a1421b3d7f8a1f021dfef76886d4f4bc5d1e | d5580e30074c3e773590741c025858650a9d802b | refs/heads/master | 2021-04-08T22:14:34.273154 | 2020-05-28T14:56:07 | 2020-05-28T14:56:07 | 248,814,377 | 1 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 599 | swift | //: [Previous](@previous)
import Foundation
//: # Chapter Three
//: ## [Monoid](https://marmelab.com/blog/2018/04/18/functional-programming-2-monoid.htmlhttps://marmelab.com/blog/2018/04/18/functional-programming-2-monoid.html)
/*:
1. Operation must combine two values and the result must also be part of the set called “magma”, and operation called “mappend”
2. Operation must be associative, no matter how you group the operation the result is the same if order is respected
3. Must possess a neutral element, “” or 0 or identity function “mempty”
*/
//: [Next](@next)
| [
-1
] |
385883b6ae29c3bd32df2664af3e1c46ba1f3a50 | 0d793f22cef83ed27a329131a853b955ffa53382 | /FirebaseComplete/Complex/Firebase/View/Design #2/SignUpViewD2.swift | 967a74809c3ff8a1f9eebe6659cfdb2e96bdff73 | [] | no_license | dhuntleypro/FirebaseComplete | 735b36d103a7bd31d279594fcea917a03a017ca3 | 333c47c0703f9f09af9fd480697e4c506a3285c3 | refs/heads/main | 2023-02-17T00:58:12.303467 | 2021-01-18T03:14:38 | 2021-01-18T03:14:38 | 329,585,497 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 3,850 | swift | //
// SignUpViewD2.swift
// FirebaseComplete
//
// Created by Darrien Huntley on 1/14/21.
//
import SwiftUI
struct SignUpViewD2: View {
@EnvironmentObject var userInfo: UserInfo
@State var user: UserViewModel = UserViewModel()
@Environment(\.presentationMode) var presentationMode
@State private var showError = false
@State private var errorString = ""
var body: some View {
VStack {
Group {
VStack(alignment: .leading) {
TextField("Full Name", text: self.$user.fullname).autocapitalization(.words)
if !user.validNameText.isEmpty {
Text(user.validNameText).font(.caption).foregroundColor(.red)
}
}
VStack(alignment: .leading) {
TextField("Email Address", text: self.$user.email).autocapitalization(.none).keyboardType(.emailAddress)
if !user.validEmailAddressText.isEmpty {
Text(user.validEmailAddressText).font(.caption).foregroundColor(.red)
}
}
VStack(alignment: .leading) {
SecureField("Password", text: self.$user.password)
if !user.validPasswordText.isEmpty {
Text(user.validPasswordText).font(.caption).foregroundColor(.red)
}
}
VStack(alignment: .leading) {
SecureField("Confirm Password", text: self.$user.confirmPassword)
if !user.passwordsMatch(_confirmPW: user.confirmPassword) {
Text(user.validConfirmPasswordText).font(.caption).foregroundColor(.red)
}
}
}.frame(width: 300)
.textFieldStyle(RoundedBorderTextFieldStyle())
VStack(spacing: 20 ) {
Button(action: {
FBAuth.createUser(withEmail: self.user.email,
name: self.user.fullname,
password: self.user.password) { (result) in
switch result {
case .failure(let error) :
self.errorString = error.localizedDescription
self.showError = true
case .success(_):
print("Account creation successful")
}
}
}) {
Text("Register")
.frame(width: 200)
.padding(.vertical, 15)
.background(Color.green)
.cornerRadius(8)
.foregroundColor(.white)
.opacity(user.isSignInComplete ? 1 : 0.75)
}
.disabled(!user.isSignInComplete)
Spacer()
}.padding()
}.padding(.top)
.alert(isPresented: $showError) {
Alert(title: Text("Error creating Account"), message: Text(self.errorString), dismissButton: .default(Text("OK")))
}
.navigationBarTitle("Sign Up", displayMode: .inline)
.navigationBarItems(trailing: Button("Dismiss") {
self.presentationMode.wrappedValue.dismiss()
})
}
}
struct SignUpViewD2_Previews: PreviewProvider {
static var previews: some View {
SignUpViewD2()
}
}
| [
-1
] |
8f8391da7c0fb5b78dfd6f9eae2e1b2b3bd72881 | ae09d13814e3c428ed433a7a5f14c8974d4568c1 | /VOSForecast/clock/model/SecondHand.swift | 4e2f1d9bd7c6bf80e099b320786d060ef029d30f | [] | no_license | vjosullivan/VOSForecast | 363fd03368c201e5124f89621431bf95c78ca9e9 | 4354480b8191689d5a3f1e838b49a5f2187fd5b3 | refs/heads/master | 2021-01-15T15:42:47.898551 | 2016-11-07T09:36:02 | 2016-11-07T09:36:02 | 52,815,807 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 816 | swift | //
// SecondHand.swift
// VOSForecast
//
// Created by Vincent O'Sullivan on 23/02/2016.
// Copyright © 2016 Vincent O'Sullivan. All rights reserved.
//
import UIKit
class SecondHand: Hand {
override init(frame: CGRect) {
super.init(frame: frame)
color = UIColor(red: 144.0/255.0, green: 212.0/255.0, blue: 132.0/255.0, alpha: 1.0)
borderColor = UIColor(red: 144.0/255.0, green: 212.0/255.0, blue: 132.0/255.0, alpha: 0.25)
backgroundColor = UIColor.clear
alpha = 1.0
width = 1.5
length = 0.95
offsetLength = 0.25
shadowEnabled = false
tag = 103
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| [
-1
] |
1ea3bb47d4c1ec59704b8ec89c72fb641b24647d | 944dff04b855580f42f5b9cc1e37363d98729f8d | /expocity/View/Main/VMainLoader.swift | ad27e558d81652c1ae6d382e7927e4f7529f13b9 | [
"MIT"
] | permissive | scotlandyard/expocity | d68984abd828613c1f38419e45e0c14b8c56510e | c848006928ad339685f1f6902f9125e1d001b3f7 | refs/heads/master | 2020-04-19T10:23:03.083656 | 2016-10-10T20:43:08 | 2016-10-10T20:43:08 | 67,320,161 | 0 | 0 | null | 2016-10-10T20:43:08 | 2016-09-04T01:45:18 | Swift | UTF-8 | Swift | false | false | 823 | swift | import UIKit
class VMainLoader:UIImageView
{
private let kAnimationDuration:TimeInterval = 1
init()
{
super.init(frame:CGRect.zero)
let images:[UIImage] = [
#imageLiteral(resourceName: "genericLoader0"),
#imageLiteral(resourceName: "genericLoader1"),
#imageLiteral(resourceName: "genericLoader2"),
#imageLiteral(resourceName: "genericLoader3")
]
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
clipsToBounds = true
animationDuration = kAnimationDuration
animationImages = images
contentMode = UIViewContentMode.center
startAnimating()
}
required init?(coder:NSCoder)
{
fatalError()
}
}
| [
-1
] |
2a2188268e8999a63048a28e4390fcfc2adce809 | 2c69a8f7d08ca9bc274b2b8af23ece418876af20 | /TinderCardDemo/TinderCardDemo/Modules/Root/TinderCardDemoBuilder.swift | cb15c6039378c4ad926e47a0117bdd7299aa5ca8 | [] | no_license | dung00275/TinderCardDemo | 7bc2e890a5f045a6d3b47a9b93a17fba9b780870 | 50d2fdf4fd1a600261557201ed1d5935ee83e0d9 | refs/heads/master | 2023-01-06T18:00:28.270541 | 2020-11-02T08:40:14 | 2020-11-02T08:40:14 | 309,111,783 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 2,214 | swift | // File name : TinderCardDemoBuilder.swift
//
// Author : Dung Vu
// Created date: 11/1/20
// Version : 1.00
// --------------------------------------------------------------
//
// --------------------------------------------------------------
import RIBs
// MARK: Dependency tree
protocol TinderCardDemoDependency: Dependency {
// todo: Declare the set of dependencies required by this RIB, but cannot be created by this RIB.
var networkRequester: RequestNetworkProtocol { get }
}
final class TinderCardDemoComponent: Component<TinderCardDemoDependency> {
/// Class's public properties.
let TinderCardDemoVC: TinderCardDemoVC
/// Class's constructor.
init(dependency: TinderCardDemoDependency, TinderCardDemoVC: TinderCardDemoVC) {
self.TinderCardDemoVC = TinderCardDemoVC
super.init(dependency: dependency)
}
/// Class's private properties.
// todo: Declare 'fileprivate' dependencies that are only used by this RIB.
}
// MARK: Builder
protocol TinderCardDemoBuildable: Buildable {
func build() -> LaunchRouting
}
final class TinderCardDemoBuilder: Builder<TinderCardDemoDependency>, TinderCardDemoBuildable {
/// Class's constructor.
override init(dependency: TinderCardDemoDependency) {
super.init(dependency: dependency)
}
// MARK: TinderCardDemoBuildable's members
func build() -> LaunchRouting {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let vc = storyboard.instantiateInitialViewController() as? TinderCardDemoVC else {
fatalError("Please implement!!!!")
}
let component = TinderCardDemoComponent(dependency: dependency, TinderCardDemoVC: vc)
let interactor = TinderCardDemoInteractor(presenter: component.TinderCardDemoVC, networkRequester: component.dependency.networkRequester)
// todo: Create builder modules builders and inject into router here.
let tinderCardDetailBuilder = TinderCardDetailBuilder(dependency: component)
return TinderCardDemoRouter(interactor: interactor, tinderCardDetailBuildable: tinderCardDetailBuilder, viewController: component.TinderCardDemoVC)
}
}
| [
-1
] |
c508c630150666d19f81feaceca75b140abdb6ed | 4bf45be1654a514c82972339751697bfb9e4a300 | /LocalSearchTemp/LocalSearchTemp/CitySearchViewController.swift | 9cfc164ce9d93c9bb925c149804d3f8a0d2b0670 | [] | no_license | amit-k-gupta/LocalSearch | 21b1cb73278fb2488d859560b47fc0316522e135 | e110fbbf9a865cdef403059027e31015e707d55b | refs/heads/master | 2020-07-06T02:08:18.600516 | 2016-11-17T20:38:44 | 2016-11-17T20:38:44 | 74,063,338 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 4,148 | swift | //
// CitySearchViewController.swift
// LocalSearchTemp
//
// Created by Amit Gupta on 20/08/16.
// Copyright © 2016 harman. All rights reserved.
//
import UIKit
class CitySearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//MARK: Properties
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var filteredCities : [String] = []
var cityList: [String] = ["Bangalore", "Indore", "Bhopal","New Delhi", "Mumbai", "Hyderabad","Pune", "Vizag", "Nagpur","Chennai", "Trivandrum", "Delhi","Raipur", "Shimla", "Dehradun"]
var searchActive : Bool = false
var selectedCity : String = ""
// MARK: Methods
override func viewDidLoad() {
super.viewDidLoad()
// let classString = #file.componentsSeparatedByString("/").last!
// NSLog("\n Class %@ \n Column %d \n Function %@ \n Line %d", classString, #column, #function, #line)
self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func viewDidAppear(animated: Bool) {
if (LSTUserProfile.sharedInstance.userName.characters.count>0) {
self.navigationItem.title = LSTUserProfile.sharedInstance.firstName
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchActive {
return filteredCities.count
}
return self.cityList.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView!.dequeueReusableCellWithIdentifier("Cell" as String!)! as UITableViewCell!
cell.backgroundColor = UIColor.purpleColor()
if searchActive {
cell.textLabel?.text = filteredCities[indexPath.row]
} else {
cell.textLabel?.text = cityList[indexPath.row]
}
return cell
}
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if searchActive {
self.selectedCity = filteredCities[indexPath.row]
} else {
self.selectedCity = cityList[indexPath.row]
}
self.performSegueWithIdentifier("LSTFilter", sender: self);
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Make sure your segue name in storyboard is the same as this line
if (segue.identifier == "LSTFilter"){
// Get reference to the destination view controller
let vc = segue.destinationViewController as! CategorySearchViewController
vc.selectedCity = self.selectedCity
}
}
//MARK: UISearchBarDelegate
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filteredCities = cityList.filter({ (text) -> Bool in
let tmp: NSString = text
let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return range.location != NSNotFound
})
if(filteredCities.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.tableView.reloadData()
}
}
| [
-1
] |
3b2fe2f64314b282976fd9a3300dbff2c6cec3d5 | 6c1291b3a5e300e02ac76b0bdb59e556fed6aa63 | /FSNotes/Helpers/NotesTextProcessor.swift | b6a6d76f4c587d7cdfba36b66500e6ee32570362 | [
"MIT"
] | permissive | guoc/fsnotes | 1247d13a01416506d88c92861f71cc4e62fbf7bf | cddfee3a270f90456fba7f3025b34c88e15fcadd | refs/heads/master | 2022-12-27T13:49:37.617212 | 2020-10-19T02:26:15 | 2020-10-19T02:26:15 | 299,908,764 | 0 | 0 | null | 2020-09-30T12:17:31 | 2020-09-30T12:17:31 | null | UTF-8 | Swift | false | false | 69,539 | swift | //
// NotesTextStorage.swift
// FSNotes
//
// Created by Oleksandr Glushchenko on 12/26/17.
// Copyright © 2017 Oleksandr Glushchenko. All rights reserved.
//
import Highlightr
#if os(OSX)
import Cocoa
import MASShortcut
#else
import UIKit
import NightNight
#endif
public class NotesTextProcessor {
#if os(OSX)
typealias Color = NSColor
typealias Image = NSImage
typealias Font = NSFont
public static var fontColor: NSColor {
get {
if UserDefaultsManagement.appearanceType != AppearanceType.Custom, #available(OSX 10.13, *) {
return NSColor(named: "mainText")!
} else {
return UserDefaultsManagement.fontColor
}
}
}
#else
typealias Color = UIColor
typealias Image = UIImage
typealias Font = UIFont
#endif
// MARK: Syntax highlight customisation
/**
Color used to highlight markdown syntax. Default value is light grey.
*/
public static var syntaxColor = Color.lightGray
#if os(OSX)
public static var font: NSFont {
get {
return UserDefaultsManagement.noteFont
}
}
public static var codeBackground: NSColor {
get {
if UserDefaultsManagement.appearanceType != AppearanceType.Custom, #available(OSX 10.13, *) {
return NSColor(named: "code")!
} else {
return NSColor(red:0.97, green:0.97, blue:0.97, alpha:1.0)
}
}
}
open var highlightColor: NSColor {
get {
if UserDefaultsManagement.appearanceType != AppearanceType.Custom, #available(OSX 10.13, *) {
return NSColor(named: "highlight")!
} else {
return NSColor(red:1.00, green:0.90, blue:0.70, alpha:1.0)
}
}
}
public static var quoteColor: NSColor {
get {
if UserDefaultsManagement.appearanceType != AppearanceType.Custom, #available(OSX 10.13, *) {
return NSColor(named: "quoteColor")!
} else {
return NSColor.darkGray
}
}
}
public static var underlineColor: NSColor {
get {
if UserDefaultsManagement.appearanceType != AppearanceType.Custom, #available(OSX 10.13, *) {
return NSColor(named: "underlineColor")!
} else {
return NSColor.black
}
}
}
#else
public static var font: UIFont {
get {
let font = UserDefaultsManagement.noteFont!
if #available(iOS 11.0, *), UserDefaultsManagement.dynamicTypeFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
return fontMetrics.scaledFont(for: font)
}
return font
}
}
public static var codeBackground: UIColor {
get {
if NightNight.theme == .night {
return UIColor(red:0.27, green:0.27, blue:0.27, alpha:1.0)
} else {
return UIColor(red:0.94, green:0.95, blue:0.95, alpha:1.0)
}
}
}
open var highlightColor: UIColor {
get {
if NightNight.theme == .night {
return UIColor(red:0.20, green:0.55, blue:0.07, alpha:1.0)
} else {
return UIColor(red:1.00, green:0.90, blue:0.70, alpha:1.0)
}
}
}
public static var quoteColor: UIColor {
get {
return UIColor.darkGray
}
}
public static var underlineColor: UIColor {
get {
return UIColor.black
}
}
#endif
/**
Quote indentation in points. Default 20.
*/
open var quoteIndendation : CGFloat = 20
#if os(OSX)
public static var codeFont = NSFont(name: UserDefaultsManagement.codeFontName, size: CGFloat(UserDefaultsManagement.codeFontSize))
#else
static var codeFont: UIFont? {
get {
if var font = UIFont(name: "Source Code Pro", size: CGFloat(UserDefaultsManagement.fontSize)) {
if #available(iOS 11.0, *), UserDefaultsManagement.dynamicTypeFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
font = fontMetrics.scaledFont(for: font)
}
return font
}
return nil
}
}
#endif
/**
If the markdown syntax should be hidden or visible
*/
public static var hideSyntax = false
private var note: Note?
private var storage: NSTextStorage?
private var range: NSRange?
private var width: CGFloat?
init(note: Note? = nil, storage: NSTextStorage? = nil, range: NSRange? = nil) {
self.note = note
self.storage = storage
self.range = range
}
public static func getFencedCodeBlockRange(paragraphRange: NSRange, string: NSMutableAttributedString) -> NSRange? {
guard UserDefaultsManagement.codeBlockHighlight else { return nil }
let regex = try! NSRegularExpression(pattern: NotesTextProcessor._codeQuoteBlockPattern, options: [
NSRegularExpression.Options.allowCommentsAndWhitespace,
NSRegularExpression.Options.anchorsMatchLines
])
var foundRange: NSRange? = nil
regex.enumerateMatches(
in: string.string,
options: NSRegularExpression.MatchingOptions(),
range: NSRange(0..<string.length),
using: { (result, matchingFlags, stop) -> Void in
guard let r = result else {
return
}
if r.range.intersection(paragraphRange) != nil {
if r.range.upperBound < string.length {
foundRange = NSRange(location: r.range.location, length: r.range.length)
} else {
foundRange = r.range
}
stop.pointee = true
}
}
)
return foundRange
}
public static var hl: Highlightr? = nil
public static func getHighlighter() -> Highlightr? {
if let instance = self.hl {
return instance
}
guard let highlightr = Highlightr() else {
return nil
}
highlightr.setTheme(to: UserDefaultsManagement.codeTheme)
self.hl = highlightr
return highlightr
}
#if os(iOS)
public static func updateFont(note: Note) {
if var font = UserDefaultsManagement.noteFont {
if #available(iOS 11.0, *), UserDefaultsManagement.dynamicTypeFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
font = fontMetrics.scaledFont(for: font)
}
note.content.addAttribute(.font, value: font, range: NSRange(0..<note.content.length))
}
}
#endif
public static func highlightCode(attributedString: NSMutableAttributedString, range: NSRange, language: String? = nil) {
guard let highlighter = NotesTextProcessor.getHighlighter() else { return }
let codeString = attributedString.mutableString.substring(with: range)
let preDefinedLanguage = language ?? getLanguage(codeString)
if let code = highlighter.highlight(codeString, as: preDefinedLanguage) {
if (range.location + range.length) > attributedString.length {
return
}
if attributedString.length >= range.upperBound && (code.string != attributedString.mutableString.substring(with: range)) {
return
}
code.enumerateAttributes(
in: NSMakeRange(0, code.length),
options: [],
using: { (attrs, locRange, stop) in
var fixedRange = NSMakeRange(range.location+locRange.location, locRange.length)
fixedRange.length = (fixedRange.location + fixedRange.length < attributedString.length) ? fixedRange.length : attributedString.length-fixedRange.location
fixedRange.length = (fixedRange.length >= 0) ? fixedRange.length : 0
for (key, value) in attrs {
attributedString.addAttribute(key, value: value, range: fixedRange)
}
guard let font = NotesTextProcessor.codeFont else { return }
attributedString.addAttribute(.font, value: font, range: fixedRange)
attributedString.fixAttributes(in: fixedRange)
}
)
attributedString.mutableString.enumerateSubstrings(in: range, options: .byParagraphs) { string, range, _, _ in
let rangeNewline = range.upperBound == attributedString.length ? range : NSRange(range.location..<range.upperBound + 1)
attributedString.addAttribute(.backgroundColor, value: NotesTextProcessor.codeBackground, range: rangeNewline)
}
}
}
public static func applyCodeBlockStyle(attributedString: NSMutableAttributedString, range: NSRange) {
//let style = TextFormatter.getCodeParagraphStyle()
//attributedString.addAttribute(.paragraphStyle, value: style, range: range)
}
fileprivate static var quoteIndendationStyle : NSParagraphStyle {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = CGFloat(UserDefaultsManagement.editorLineSpacing)
return paragraphStyle
}
public static var languages: [String]? = nil
public static func getLanguage(_ code: String) -> String? {
if code.starts(with: "```") {
let start = code.index(code.startIndex, offsetBy: 0)
let end = code.index(code.startIndex, offsetBy: 3)
let range = start..<end
let paragraphRange = code.paragraphRange(for: range)
let detectedLang =
code[paragraphRange]
.replacingOccurrences(of: "```", with: "")
.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
self.languages = self.getHighlighter()?.supportedLanguages()
if let lang = self.languages, lang.contains(detectedLang) {
return detectedLang
}
}
return nil
}
/**
Coverts App links:`[[Link Title]]` to Markdown: `[Link](fsnotes://find/link%20title)`
- parameter content: A string containing CommonMark Markdown
- returns: Content string with converted links
*/
public static func convertAppLinks(in content: String) -> String {
var resultString = content
NotesTextProcessor.appUrlRegex.matches(content, range: NSRange(location: 0, length: content.count), completion: { (result) -> (Void) in
guard let innerRange = result?.range else { return }
var _range = innerRange
_range.location = _range.location + 2
_range.length = _range.length - 4
let lintTitle = (content as NSString).substring(with: _range)
let allowedCharacters = CharacterSet(bitmapRepresentation: CharacterSet.urlPathAllowed.bitmapRepresentation)
let escapedString = lintTitle.addingPercentEncoding(withAllowedCharacters: allowedCharacters)!
let newLink = "[\(lintTitle)](fsnotes://find?id=\(escapedString))"
resultString = resultString.replacingOccurrences(of: "[[\(lintTitle)]]", with: newLink)
})
return resultString
}
public static func convertAppTags(in content: NSMutableAttributedString) -> NSMutableAttributedString {
let attributedString = content.mutableCopy() as! NSMutableAttributedString
let range = NSRange(0..<content.string.count)
let tagQuery = "fsnotes://open/?tag="
NotesTextProcessor.tagsInlineRegex.matches(content.string, range: range) { (result) -> Void in
guard var range = result?.range(at: 1) else { return }
range = NSRange(location: range.location - 1, length: range.length + 1)
var substring = attributedString.mutableString.substring(with: range)
substring = substring
.replacingOccurrences(of: "#", with: "")
.replacingOccurrences(of: "\n", with: "")
.trim()
if ["!", "?", ";", ":", ".", ","].contains(substring.last) {
range = NSRange(location: range.location, length: range.length - 1)
substring = String(substring.dropLast())
}
guard let tag = substring.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return }
attributedString.addAttribute(.link, value: "\(tagQuery)\(tag)", range: range)
}
attributedString.enumerateAttribute(.link, in: range) { (value, range, _) in
if let value = value as? String, value.starts(with: tagQuery) {
if let tag = value
.replacingOccurrences(of: tagQuery, with: "")
.removingPercentEncoding
{
let link = "[#\(tag)](\(value))"
attributedString.replaceCharacters(in: range, with: link)
}
}
}
return attributedString
}
public static func highlight(note: Note) {
highlightMarkdown(attributedString: note.content, note: note)
highlightFencedAndIndentCodeBlocks(attributedString: note.content)
}
public static func highlightFencedAndIndentCodeBlocks(attributedString: NSMutableAttributedString) {
let range = NSRange(0..<attributedString.length)
if UserDefaultsManagement.codeBlockHighlight {
var fencedRanges = [NSRange]()
// Fenced code block
let regexFencedCodeBlock = try! NSRegularExpression(pattern: self._codeQuoteBlockPattern, options: [
.allowCommentsAndWhitespace,
.anchorsMatchLines
])
regexFencedCodeBlock.enumerateMatches(
in: attributedString.string,
options: NSRegularExpression.MatchingOptions(),
range: range,
using: { (result, matchingFlags, stop) -> Void in
guard let r = result else { return }
fencedRanges.append(r.range)
NotesTextProcessor.highlightCode(attributedString: attributedString, range: r.range)
NotesTextProcessor.highlightFencedBackTick(range: r.range, attributedString: attributedString)
})
// Indent code blocks
if UserDefaultsManagement.indentedCodeBlockHighlighting {
let codeTextProcessor = CodeTextProcessor(textStorage: attributedString)
if let codeBlockRanges = codeTextProcessor.getCodeBlockRanges() {
for range in codeBlockRanges {
if isIntersect(fencedRanges: fencedRanges, indentRange: range) {
continue
}
NotesTextProcessor.highlightCode(attributedString: attributedString, range: range)
}
}
}
}
}
public static func highlightFencedBackTick(range: NSRange, attributedString: NSMutableAttributedString) {
let code = attributedString.mutableString.substring(with: range)
let language = NotesTextProcessor.getLanguage(code)
var length = 3
if let langLength = language?.count {
length += langLength
}
let openRange = NSRange(location: range.location, length: length)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: openRange)
let closeRange = NSRange(location: range.upperBound - 4, length: 3)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: closeRange)
if let langLength = language?.count {
let range = NSRange(location: range.location + 3, length: langLength)
attributedString.addAttribute(.foregroundColor, value: Color.red, range: range)
}
}
public static func isIntersect(fencedRanges: [NSRange], indentRange: NSRange) -> Bool {
for fencedRange in fencedRanges {
if fencedRange.intersection(indentRange) != nil {
return true
}
}
return false
}
public static func minimalHighlight(attributedString: NSMutableAttributedString, paragraphRange: NSRange? = nil, note: Note) {
let paragraphRange = paragraphRange ?? NSRange(0..<attributedString.length)
attributedString.addAttribute(.font, value: font, range: paragraphRange)
attributedString.fixAttributes(in: paragraphRange)
#if os(iOS)
if NightNight.theme == .night {
attributedString.addAttribute(.foregroundColor, value: UIColor.white, range: paragraphRange)
} else {
attributedString.addAttribute(.foregroundColor, value: UserDefaultsManagement.fontColor, range: paragraphRange)
}
#else
attributedString.addAttribute(.foregroundColor, value: fontColor, range: paragraphRange)
attributedString.enumerateAttribute(.foregroundColor, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if (value as? NSColor) != nil {
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.fontColor, range: range)
}
}
#endif
}
public static func highlightMarkdown(attributedString: NSMutableAttributedString, paragraphRange: NSRange? = nil, note: Note) {
let paragraphRange = paragraphRange ?? NSRange(0..<attributedString.length)
let isFullScan = attributedString.length == paragraphRange.upperBound && paragraphRange.lowerBound == 0
let string = attributedString.string
let codeFont = NotesTextProcessor.codeFont(CGFloat(UserDefaultsManagement.fontSize))
let quoteFont = NotesTextProcessor.quoteFont(CGFloat(UserDefaultsManagement.fontSize))
#if os(OSX)
let boldFont = NSFont.boldFont()
let italicFont = NSFont.italicFont()
let hiddenFont = NSFont.systemFont(ofSize: 0.1)
#else
var boldFont: UIFont {
get {
var font = UserDefaultsManagement.noteFont.bold()
font.withSize(CGFloat(UserDefaultsManagement.fontSize))
if #available(iOS 11.0, *), UserDefaultsManagement.dynamicTypeFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
font = fontMetrics.scaledFont(for: font)
}
return font
}
}
var italicFont: UIFont {
get {
var font = UserDefaultsManagement.noteFont.italic()
font.withSize(CGFloat(UserDefaultsManagement.fontSize))
if #available(iOS 11.0, *), UserDefaultsManagement.dynamicTypeFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
font = fontMetrics.scaledFont(for: font)
}
return font
}
}
let hiddenFont = UIFont.systemFont(ofSize: 0.1)
#endif
let hiddenColor = Color.clear
let hiddenAttributes: [NSAttributedString.Key : Any] = [
.font : hiddenFont,
.foregroundColor : hiddenColor
]
func hideSyntaxIfNecessary(range: @autoclosure () -> NSRange) {
guard NotesTextProcessor.hideSyntax else { return }
attributedString.addAttributes(hiddenAttributes, range: range())
}
attributedString.enumerateAttribute(.link, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if value != nil && attributedString.attribute(.attachment, at: range.location, effectiveRange: nil) == nil {
attributedString.removeAttribute(.link, range: range)
}
}
attributedString.enumerateAttribute(.strikethroughStyle, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if value != nil {
attributedString.removeAttribute(.strikethroughStyle, range: range)
}
}
attributedString.addAttribute(.font, value: font, range: paragraphRange)
attributedString.fixAttributes(in: paragraphRange)
#if os(iOS)
if NightNight.theme == .night {
attributedString.addAttribute(.foregroundColor, value: UIColor.white, range: paragraphRange)
} else {
attributedString.addAttribute(.foregroundColor, value: UserDefaultsManagement.fontColor, range: paragraphRange)
}
#else
attributedString.addAttribute(.foregroundColor, value: fontColor, range: paragraphRange)
attributedString.enumerateAttribute(.foregroundColor, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if (value as? NSColor) != nil {
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.fontColor, range: range)
}
}
#endif
// We detect and process inline links not formatted
NotesTextProcessor.autolinkRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard var range = result?.range else { return }
var substring = attributedString.mutableString.substring(with: range)
guard substring.lengthOfBytes(using: .utf8) > 0 && URL(string: substring) != nil else { return }
if ["!", "?", ";", ":", ".", ","].contains(substring.last) {
range = NSRange(location: range.location, length: range.length - 1)
substring = String(substring.dropLast())
}
attributedString.addAttribute(.link, value: substring, range: range)
if NotesTextProcessor.hideSyntax {
NotesTextProcessor.autolinkPrefixRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.font, value: hiddenFont, range: innerRange)
attributedString.fixAttributes(in: innerRange)
attributedString.addAttribute(.foregroundColor, value: hiddenColor, range: innerRange)
}
}
}
// We detect and process underlined headers
NotesTextProcessor.headersSetextRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: boldFont, range: range)
attributedString.fixAttributes(in: range)
NotesTextProcessor.headersSetextUnderlineRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: NSMakeRange(innerRange.location, innerRange.length))
}
}
// We detect and process dashed headers
NotesTextProcessor.headersAtxRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: boldFont, range: range)
attributedString.fixAttributes(in: range)
NotesTextProcessor.headersAtxOpeningRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
let syntaxRange = NSMakeRange(innerRange.location, innerRange.length + 1)
hideSyntaxIfNecessary(range: syntaxRange)
}
NotesTextProcessor.headersAtxClosingRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
}
// We detect and process reference links
NotesTextProcessor.referenceLinkRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: range)
}
// We detect and process lists
NotesTextProcessor.listRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
NotesTextProcessor.listOpeningRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
}
// We detect and process anchors (links)
NotesTextProcessor.anchorRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: codeFont, range: range)
attributedString.fixAttributes(in: range)
NotesTextProcessor.openingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.closingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.parenRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
let initialSyntaxRange = NSMakeRange(innerRange.location, 1)
let finalSyntaxRange = NSMakeRange(innerRange.location + innerRange.length - 1, 1)
hideSyntaxIfNecessary(range: initialSyntaxRange)
hideSyntaxIfNecessary(range: finalSyntaxRange)
}
}
#if NOT_EXTENSION || os(OSX)
// We detect and process inline anchors (links)
NotesTextProcessor.anchorInlineRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: codeFont, range: range)
attributedString.fixAttributes(in: range)
var destinationLink : String?
NotesTextProcessor.coupleRoundRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
guard let linkRange = result?.range(at: 3), linkRange.length > 0 else { return }
var substring = attributedString.mutableString.substring(with: linkRange)
guard substring.count > 0 else { return }
guard let note = EditTextView.note else { return }
if substring.starts(with: "/i/") || substring.starts(with: "/files/"), let path = note.project.url.appendingPathComponent(substring).path.removingPercentEncoding {
substring = "file://" + path
} else if note.isTextBundle() && substring.starts(with: "assets/"), let path = note.getURL().appendingPathComponent(substring).path.removingPercentEncoding {
substring = "file://" + path
}
destinationLink = substring
attributedString.addAttribute(.link, value: substring, range: linkRange)
hideSyntaxIfNecessary(range: innerRange)
}
NotesTextProcessor.openingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
NotesTextProcessor.closingSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
guard let destinationLinkString = destinationLink else { return }
NotesTextProcessor.coupleSquareRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
var _range = innerRange
_range.location = _range.location + 1
_range.length = _range.length - 2
let substring = attributedString.mutableString.substring(with: _range)
guard substring.lengthOfBytes(using: .utf8) > 0 else { return }
attributedString.addAttribute(.link, value: destinationLinkString, range: _range)
}
}
#endif
NotesTextProcessor.imageRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: codeFont, range: range)
attributedString.fixAttributes(in: range)
// TODO: add image attachment
if NotesTextProcessor.hideSyntax {
attributedString.addAttribute(.font, value: hiddenFont, range: range)
}
NotesTextProcessor.imageOpeningSquareRegex.matches(string, range: paragraphRange) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.imageClosingSquareRegex.matches(string, range: paragraphRange) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
}
// We detect and process app urls [[link]]
NotesTextProcessor.appUrlRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let innerRange = result?.range else { return }
var _range = innerRange
_range.location = _range.location + 2
_range.length = _range.length - 4
let appLink = attributedString.mutableString.substring(with: _range)
if let link = appLink.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) {
#if os(iOS)
let color =
NightNight.theme == .night
? UIColor(red: 0.00, green: 0.45, blue: 0.15, alpha: 1.00)
: UIColor(red: 0.29, green: 0.35, blue: 0.60, alpha: 1.00)
attributedString.addAttribute(.foregroundColor, value: color, range: innerRange)
#endif
attributedString.addAttribute(.link, value: "fsnotes://find?id=" + link, range: _range)
if let range = result?.range(at: 0) {
attributedString.addAttribute(.foregroundColor, value: Color.gray, range: range)
}
if let range = result?.range(at: 2) {
attributedString.addAttribute(.foregroundColor, value: Color.gray, range: range)
}
}
}
// We detect and process quotes
NotesTextProcessor.blockQuoteRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.font, value: quoteFont, range: range)
attributedString.fixAttributes(in: range)
attributedString.addAttribute(.foregroundColor, value: quoteColor, range: range)
attributedString.addAttribute(.paragraphStyle, value: quoteIndendationStyle, range: range)
NotesTextProcessor.blockQuoteOpeningRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
hideSyntaxIfNecessary(range: innerRange)
}
}
// We detect and process italics
NotesTextProcessor.italicRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
if NotesTextProcessor.isLink(attributedString: attributedString, range: range) {
return
}
attributedString.addAttribute(.font, value: italicFont, range: range)
NotesTextProcessor.boldRegex.matches(string, range: range) { (result) -> Void in
guard let range = result?.range else { return }
let boldItalic = Font.addBold(font: italicFont)
attributedString.addAttribute(.font, value: boldItalic, range: range)
}
attributedString.fixAttributes(in: range)
let preRange = NSMakeRange(range.location, 1)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
hideSyntaxIfNecessary(range: preRange)
let postRange = NSMakeRange(range.location + range.length - 1, 1)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
hideSyntaxIfNecessary(range: postRange)
}
// We detect and process bolds
NotesTextProcessor.boldRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
if NotesTextProcessor.isLink(attributedString: attributedString, range: range) {
return
}
if let font = attributedString.attributedSubstring(from: range).attribute(.font, at: 0, effectiveRange: nil) as? Font, font.isItalic {
} else {
attributedString.addAttribute(.font, value: boldFont, range: range)
NotesTextProcessor.italicRegex.matches(string, range: range) { (result) -> Void in
guard let range = result?.range else { return }
let boldItalic = Font.addItalic(font: boldFont)
attributedString.addAttribute(.font, value: boldItalic, range: range)
}
}
attributedString.fixAttributes(in: range)
let preRange = NSMakeRange(range.location, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
hideSyntaxIfNecessary(range: preRange)
let postRange = NSMakeRange(range.location + range.length - 2, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
hideSyntaxIfNecessary(range: postRange)
}
// We detect and process bolds
NotesTextProcessor.strikeRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
attributedString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: range.location + 2, length: range.length - 4))
attributedString.fixAttributes(in: range)
let preRange = NSMakeRange(range.location, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: preRange)
hideSyntaxIfNecessary(range: preRange)
let postRange = NSMakeRange(range.location + range.length - 2, 2)
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: postRange)
hideSyntaxIfNecessary(range: postRange)
}
// We detect and process inline mailto links not formatted
NotesTextProcessor.autolinkEmailRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
let substring = attributedString.mutableString.substring(with: range)
guard substring.lengthOfBytes(using: .utf8) > 0, URL(string: substring) != nil else { return }
attributedString.addAttribute(.link, value: substring, range: range)
if NotesTextProcessor.hideSyntax {
NotesTextProcessor.mailtoRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.font, value: hiddenFont, range: innerRange)
attributedString.addAttribute(.foregroundColor, value: hiddenColor, range: innerRange)
}
}
}
// Todo
NotesTextProcessor.todoInlineRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
let substring = attributedString.mutableString.substring(with: range)
if substring.contains("- [x]") {
let strikeRange = attributedString.mutableString.paragraphRange(for: range)
attributedString.addAttribute(.strikethroughStyle, value: 1, range: strikeRange)
}
}
// Inline tags
NotesTextProcessor.tagsInlineRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard var range = result?.range(at: 1) else { return }
range = NSRange(location: range.location - 1, length: range.length + 1)
var substring = attributedString.mutableString.substring(with: range)
substring = substring
.replacingOccurrences(of: "#", with: "")
.replacingOccurrences(of: "\n", with: "")
.trim()
if ["!", "?", ";", ":", ".", ","].contains(substring.last) {
range = NSRange(location: range.location, length: range.length - 1)
substring = String(substring.dropLast())
}
guard let tag = substring.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return }
attributedString.addAttribute(.link, value: "fsnotes://open/?tag=\(tag)", range: range)
}
if !UserDefaultsManagement.liveImagesPreview {
// We detect and process inline images
NotesTextProcessor.imageInlineRegex.matches(string, range: paragraphRange) { (result) -> Void in
guard let range = result?.range else { return }
if let linkRange = result?.range(at: 3) {
let link = attributedString.mutableString.substring(with: linkRange).removingPercentEncoding
if let link = link, let url = note.getImageUrl(imageName: link) {
attributedString.addAttribute(.link, value: url, range: linkRange)
}
}
attributedString.addAttribute(.font, value: codeFont, range: range)
NotesTextProcessor.imageOpeningSquareRegex.matches(string, range: paragraphRange) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.imageClosingSquareRegex.matches(string, range: paragraphRange) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.parenRegex.matches(string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
attributedString.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
}
}
attributedString.enumerateAttribute(.attachment, in: paragraphRange, options: []) { (value, range, stop) -> Void in
if value != nil, let todo = attributedString.attribute(.todo, at: range.location, effectiveRange: nil) {
let strikeRange = attributedString.mutableString.paragraphRange(for: range)
attributedString.addAttribute(.strikethroughStyle, value: todo, range: strikeRange)
}
}
if isFullScan {
checkBackTick(styleApplier: attributedString)
}
}
public static func checkBackTick(styleApplier: NSMutableAttributedString, paragraphRange: NSRange? = nil) {
guard UserDefaultsManagement.codeBlockHighlight else { return }
var range = NSRange(0..<styleApplier.length)
if let parRange = paragraphRange {
range = parRange
}
styleApplier.enumerateAttribute(.backgroundColor, in: range) { (value, innerRange, _) in
if value != nil, let font = UserDefaultsManagement.noteFont {
styleApplier.removeAttribute(.backgroundColor, range: innerRange)
styleApplier.addAttribute(.font, value: font, range: innerRange)
styleApplier.fixAttributes(in: innerRange)
}
}
if let codeFont = NotesTextProcessor.codeFont {
NotesTextProcessor.codeSpanRegex.matches(styleApplier.string, range: range) { (result) -> Void in
guard let range = result?.range else { return }
styleApplier.addAttribute(.font, value: codeFont, range: range)
styleApplier.addAttribute(.backgroundColor, value: NotesTextProcessor.codeBackground, range: range)
NotesTextProcessor.codeSpanOpeningRegex.matches(styleApplier.string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
styleApplier.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
NotesTextProcessor.codeSpanClosingRegex.matches(styleApplier.string, range: range) { (innerResult) -> Void in
guard let innerRange = innerResult?.range else { return }
styleApplier.addAttribute(.foregroundColor, value: NotesTextProcessor.syntaxColor, range: innerRange)
}
}
}
}
public static func getAttachPrefix(url: URL? = nil) -> String {
if let url = url, !url.isImage {
return "/files/"
}
return "/i/"
}
public static func isLink(attributedString: NSAttributedString, range: NSRange) -> Bool {
return attributedString.attributedSubstring(from: range).attribute(.link, at: 0, effectiveRange: nil) != nil
}
/// Tabs are automatically converted to spaces as part of the transform
/// this constant determines how "wide" those tabs become in spaces
public static let _tabWidth = 4
// MARK: Headers
/*
Head
======
Subhead
-------
*/
fileprivate static let headerSetextPattern = [
"^(.+?)",
"\\p{Z}*",
"\\n",
"(==+|--+)", // $1 = string of ='s or -'s
"\\p{Z}*",
"\\n|\\Z"
].joined(separator: "\n")
public static let headersSetextRegex = MarklightRegex(pattern: headerSetextPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let setextUnderlinePattern = [
"(==+|--+) # $1 = string of ='s or -'s",
"\\p{Z}*$"
].joined(separator: "\n")
public static let headersSetextUnderlineRegex = MarklightRegex(pattern: setextUnderlinePattern, options: [.allowCommentsAndWhitespace])
/*
# Head
## Subhead ##
*/
fileprivate static let headerAtxPattern = [
"^(\\#{1,6}\\ ) # $1 = string of #'s",
"\\p{Z}*",
"(.+?) # $2 = Header text",
"\\p{Z}*",
"\\#* # optional closing #'s (not counted)",
"(?:\\n|\\Z)"
].joined(separator: "\n")
public static let headersAtxRegex = MarklightRegex(pattern: headerAtxPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let headersAtxOpeningPattern = [
"^(\\#{1,6}\\ )"
].joined(separator: "\n")
public static let headersAtxOpeningRegex = MarklightRegex(pattern: headersAtxOpeningPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let headersAtxClosingPattern = [
"\\#{1,6}\\ \\n+"
].joined(separator: "\n")
public static let headersAtxClosingRegex = MarklightRegex(pattern: headersAtxClosingPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
// MARK: Reference links
/*
TODO: we don't know how reference links are formed
*/
fileprivate static let referenceLinkPattern = [
"^\\p{Z}{0,\(_tabWidth - 1)}\\[([^\\[\\]]+)\\]: # id = $1",
" \\p{Z}*",
" \\n? # maybe *one* newline",
" \\p{Z}*",
"<?(\\S+?)>? # url = $2",
" \\p{Z}*",
" \\n? # maybe one newline",
" \\p{Z}*",
"(?:",
" (?<=\\s) # lookbehind for whitespace",
" [\"(]",
" (.+?) # title = $3",
" [\")]",
" \\p{Z}*",
")? # title is optional",
"(?:\\n|\\Z)"
].joined(separator: "")
public static let referenceLinkRegex = MarklightRegex(pattern: referenceLinkPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
// MARK: Lists
/*
* First element
* Second element
*/
fileprivate static let _markerUL = "[*+-]"
fileprivate static let _markerOL = "[0-9-]+[.]"
fileprivate static let _listMarker = "(?:\\p{Z}|\\t)*(?:\(_markerUL)|\(_markerOL))"
fileprivate static let _listSingleLinePattern = "^(?:\\p{Z}|\\t)*((?:[*+-]|\\d+[.]))\\p{Z}+"
public static let listRegex = MarklightRegex(pattern: _listSingleLinePattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
public static let listOpeningRegex = MarklightRegex(pattern: _listMarker, options: [.allowCommentsAndWhitespace])
// MARK: Anchors
/*
[Title](http://example.com)
*/
fileprivate static let anchorPattern = [
"( # wrap whole match in $1",
" \\[",
" (\(NotesTextProcessor.getNestedBracketsPattern())) # link text = $2",
" \\]",
"",
" \\p{Z}? # one optional space",
" (?:\\n\\p{Z}*)? # one optional newline followed by spaces",
"",
" \\[",
" (.*?) # id = $3",
" \\]",
")"
].joined(separator: "\n")
public static let anchorRegex = MarklightRegex(pattern: anchorPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let opneningSquarePattern = [
"(\\[)"
].joined(separator: "\n")
public static let openingSquareRegex = MarklightRegex(pattern: opneningSquarePattern, options: [.allowCommentsAndWhitespace])
fileprivate static let closingSquarePattern = [
"\\]"
].joined(separator: "\n")
public static let closingSquareRegex = MarklightRegex(pattern: closingSquarePattern, options: [.allowCommentsAndWhitespace])
fileprivate static let coupleSquarePattern = [
"\\[(.*?)\\]"
].joined(separator: "\n")
public static let coupleSquareRegex = MarklightRegex(pattern: coupleSquarePattern, options: [])
fileprivate static let coupleRoundPattern = [
".*(?:\\])\\((.+)\\)"
].joined(separator: "\n")
public static let coupleRoundRegex = MarklightRegex(pattern: coupleRoundPattern, options: [])
fileprivate static let parenPattern = [
"(",
"\\( # literal paren",
" \\p{Z}*",
" (\(NotesTextProcessor.getNestedParensPattern())) # href = $3",
" \\p{Z}*",
" ( # $4",
" (['\"]) # quote char = $5",
" (.*?) # title = $6",
" \\5 # matching quote",
" \\p{Z}*",
" )? # title is optional",
" \\)",
")"
].joined(separator: "\n")
public static let parenRegex = MarklightRegex(pattern: parenPattern, options: [.allowCommentsAndWhitespace])
fileprivate static let anchorInlinePattern = [
"( # wrap whole match in $1",
" \\[",
" (\(NotesTextProcessor.getNestedBracketsPattern())) # link text = $2",
" \\]",
" \\( # literal paren",
" \\p{Z}*",
" (\(NotesTextProcessor.getNestedParensPattern())) # href = $3",
" \\p{Z}*",
" ( # $4",
" (['\"]) # quote char = $5",
" (.*?) # title = $6",
" \\5 # matching quote",
" \\p{Z}* # ignore any spaces between closing quote and )",
" )? # title is optional",
" \\)",
")"
].joined(separator: "\n")
public static let anchorInlineRegex = MarklightRegex(pattern: anchorInlinePattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
// Mark: Images
/*

*/
fileprivate static let imagePattern = [
"( # wrap whole match in $1",
"!\\[",
" (.*?) # alt text = $2",
"\\]",
"",
"\\p{Z}? # one optional space",
"(?:\\n\\p{Z}*)? # one optional newline followed by spaces",
"",
"\\[",
" (.*?) # id = $3",
"\\]",
"",
")"
].joined(separator: "\n")
public static let imageRegex = MarklightRegex(pattern: imagePattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let imageOpeningSquarePattern = [
"(!\\[)"
].joined(separator: "\n")
public static let imageOpeningSquareRegex = MarklightRegex(pattern: imageOpeningSquarePattern, options: [.allowCommentsAndWhitespace])
fileprivate static let imageClosingSquarePattern = [
"(\\])"
].joined(separator: "\n")
public static let imageClosingSquareRegex = MarklightRegex(pattern: imageClosingSquarePattern, options: [.allowCommentsAndWhitespace])
fileprivate static let imageInlinePattern = [
"( # wrap whole match in $1",
" !\\[",
" ([^\\[\\]]*?) # alt text = $2",
" \\]",
" \\s? # one optional whitespace character",
" \\( # literal paren",
" \\p{Z}*",
" (\(NotesTextProcessor.getNestedParensPattern())) # href = $3",
" \\p{Z}*",
" ( # $4",
" (['\"]) # quote char = $5",
" (.*?) # title = $6",
" \\5 # matching quote",
" \\p{Z}*",
" )? # title is optional",
" \\)",
")"
].joined(separator: "\n")
public static let imageInlineRegex = MarklightRegex(pattern: imageInlinePattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let tagsPattern = "(?:\\A|\\s)\\#([^\\s\\!\\#\\:\\[\\\"\\(\\;\\,]+)"
public static let tagsInlineRegex = MarklightRegex(pattern: tagsPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let todoInlinePattern = "(^(-\\ \\[(?:\\ |x)\\])\\ )"
public static let todoInlineRegex = MarklightRegex(pattern: todoInlinePattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let allTodoInlinePattern = "((-\\ \\[(?:\\ |x)\\])\\ )"
public static let allTodoInlineRegex = MarklightRegex(pattern: allTodoInlinePattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
// MARK: Code
/*
```
Code
```
Code
*/
public static let _codeQuoteBlockPattern = [
"(?<=\\n|\\A)",
"(^```[\\S\\ \\(\\)]*\\n[\\s\\S]*?\\n```(?:\\n|\\Z))"
].joined(separator: "\n")
fileprivate static let codeSpanPattern = [
"(?<![\\\\`]) # Character before opening ` can't be a backslash or backtick",
"(`+) # $1 = Opening run of `",
"(?!`) # and no more backticks -- match the full run",
"(.+?) # $2 = The code block",
"(?<!`)",
"\\1",
"(?!`)"
].joined(separator: "\n")
public static let codeSpanRegex = MarklightRegex(pattern: codeSpanPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let codeSpanOpeningPattern = [
"(?<![\\\\`]) # Character before opening ` can't be a backslash or backtick",
"(`+) # $1 = Opening run of `"
].joined(separator: "\n")
public static let codeSpanOpeningRegex = MarklightRegex(pattern: codeSpanOpeningPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let codeSpanClosingPattern = [
"(?<![\\\\`]) # Character before opening ` can't be a backslash or backtick",
"(`+) # $1 = Opening run of `"
].joined(separator: "\n")
public static let codeSpanClosingRegex = MarklightRegex(pattern: codeSpanClosingPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
// MARK: Block quotes
/*
> Quoted text
*/
fileprivate static let blockQuotePattern = [
"( # Wrap whole match in $1",
" (",
" ^\\p{Z}*>\\p{Z}? # '>' at the start of a line",
" .+(?:\\n|\\Z) # rest of the first line",
" (.+(?:\\n|\\Z))* # subsequent consecutive lines",
" (?:\\n|\\Z)* # blanks",
" )+",
")"
].joined(separator: "\n")
public static let blockQuoteRegex = MarklightRegex(pattern: blockQuotePattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let blockQuoteOpeningPattern = [
"(^\\p{Z}*>\\p{Z})"
].joined(separator: "\n")
public static let blockQuoteOpeningRegex = MarklightRegex(pattern: blockQuoteOpeningPattern, options: [.anchorsMatchLines])
// MARK: App url
fileprivate static let appUrlPattern = "(\\[\\[)(.+?[\\[\\]]*)(\\]\\])"
public static let appUrlRegex = MarklightRegex(pattern: appUrlPattern, options: [.anchorsMatchLines])
// MARK: Bold
/*
**Bold**
__Bold__
*/
fileprivate static let strictBoldPattern = "(^|[\\W_])(?:(?!\\1)|(?=^))(\\*|_)\\2(?=\\S)(.*?\\S)\\2\\2(?!\\2)(?=[\\W_]|$)"
public static let strictBoldRegex = MarklightRegex(pattern: strictBoldPattern, options: [.anchorsMatchLines])
fileprivate static let boldPattern = "(\\*\\*|__) (?=\\S) (.+?[*_]*) (?<=\\S) \\1"
public static let boldRegex = MarklightRegex(pattern: boldPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let strikePattern = "(\\~\\~) (?=\\S) (.+?[~]*) (?<=\\S) \\1"
public static let strikeRegex = MarklightRegex(pattern: strikePattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
// MARK: Italic
/*
*Italic*
_Italic_
*/
fileprivate static let strictItalicPattern = "(^|[\\W_])(?:(?!\\1)|(?=^))(\\*|_)(?=\\S)((?:(?!\\2).)*?\\S)\\2(?!\\2)(?=[\\W_]|$)"
public static let strictItalicRegex = MarklightRegex(pattern: strictItalicPattern, options: [.anchorsMatchLines])
fileprivate static let italicPattern = "(\\_){1} (?=\\S) (.+?) (?<=\\S) \\1"
public static let italicRegex = MarklightRegex(pattern: italicPattern, options: [.allowCommentsAndWhitespace, .anchorsMatchLines])
fileprivate static let autolinkPattern = "((https?|ftp):[^\\)'\">\\s]+)"
public static let autolinkRegex = MarklightRegex(pattern: autolinkPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let autolinkPrefixPattern = "((https?|ftp)://)"
public static let autolinkPrefixRegex = MarklightRegex(pattern: autolinkPrefixPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let autolinkEmailPattern = [
"(?:mailto:)?",
"(",
" [-.\\w]+",
" \\@",
" [-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+",
")"
].joined(separator: "\n")
public static let autolinkEmailRegex = MarklightRegex(pattern: autolinkEmailPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
fileprivate static let mailtoPattern = "mailto:"
public static let mailtoRegex = MarklightRegex(pattern: mailtoPattern, options: [.allowCommentsAndWhitespace, .dotMatchesLineSeparators])
/// maximum nested depth of [] and () supported by the transform;
/// implementation detail
fileprivate static let _nestDepth = 6
fileprivate static var _nestedBracketsPattern = ""
fileprivate static var _nestedParensPattern = ""
/// Reusable pattern to match balanced [brackets]. See Friedl's
/// "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
fileprivate static func getNestedBracketsPattern() -> String {
// in other words [this] and [this[also]] and [this[also[too]]]
// up to _nestDepth
if (_nestedBracketsPattern.isEmpty) {
_nestedBracketsPattern = repeatString([
"(?> # Atomic matching",
"[^\\[\\]]+ # Anything other than brackets",
"|",
"\\["
].joined(separator: "\n"), _nestDepth) +
repeatString(" \\])*", _nestDepth)
}
return _nestedBracketsPattern
}
/// Reusable pattern to match balanced (parens). See Friedl's
/// "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
fileprivate static func getNestedParensPattern() -> String {
// in other words (this) and (this(also)) and (this(also(too)))
// up to _nestDepth
if (_nestedParensPattern.isEmpty) {
_nestedParensPattern = repeatString([
"(?> # Atomic matching",
"[^()\\s]+ # Anything other than parens or whitespace",
"|",
"\\("
].joined(separator: "\n"), _nestDepth) +
repeatString(" \\))*", _nestDepth)
}
return _nestedParensPattern
}
/// this is to emulate what's available in PHP
fileprivate static func repeatString(_ text: String, _ count: Int) -> String {
return Array(repeating: text, count: count).reduce("", +)
}
// We transform the user provided `codeFontName` `String` to a `NSFont`
fileprivate static func codeFont(_ size: CGFloat) -> Font {
if var font = UserDefaultsManagement.noteFont {
#if os(iOS)
if #available(iOS 11.0, *), UserDefaultsManagement.dynamicTypeFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
font = fontMetrics.scaledFont(for: font)
}
#endif
return font
} else {
#if os(OSX)
return NSFont.systemFont(ofSize: size)
#else
return UIFont.systemFont(ofSize: size)
#endif
}
}
// We transform the user provided `quoteFontName` `String` to a `NSFont`
fileprivate static func quoteFont(_ size: CGFloat) -> Font {
if var font = UserDefaultsManagement.noteFont {
#if os(iOS)
if #available(iOS 11.0, *), UserDefaultsManagement.dynamicTypeFont {
let fontMetrics = UIFontMetrics(forTextStyle: .body)
font = fontMetrics.scaledFont(for: font)
}
#endif
return font
} else {
#if os(OSX)
return NSFont.systemFont(ofSize: size)
#else
return UIFont.systemFont(ofSize: size)
#endif
}
}
public func higlightLinks() {
guard let storage = self.storage, let range = self.range else {
return
}
storage.removeAttribute(.link, range: range)
let pattern = "(https?:\\/\\/(?:www\\.|(?!www))[^\\s\\.]+\\.[^\\s]{2,}|www\\.[^\\s]+\\.[^\\s]{2,})"
let regex = try! NSRegularExpression(pattern: pattern, options: [NSRegularExpression.Options.caseInsensitive])
regex.enumerateMatches(
in: (storage.string),
options: NSRegularExpression.MatchingOptions(),
range: range,
using: { (result, matchingFlags, stop) -> Void in
if let range = result?.range {
guard storage.length >= range.location + range.length else {
return
}
var str = storage.mutableString.substring(with: range)
if str.starts(with: "www.") {
str = "http://" + str
}
guard let url = URL(string: str) else { return }
storage.addAttribute(.link, value: url, range: range)
}
}
)
// We detect and process app urls [[link]]
NotesTextProcessor.appUrlRegex.matches(storage.string, range: range) { (result) -> Void in
guard let innerRange = result?.range else { return }
let from = String.Index.init(utf16Offset: innerRange.lowerBound + 2, in: storage.string)
let to = String.Index.init(utf16Offset: innerRange.upperBound - 2, in: storage.string)
let appLink = storage.string[from..<to]
if let link = appLink.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) {
storage.addAttribute(.link, value: "fsnotes://find?id=" + link, range: innerRange)
}
}
}
func highlightKeyword(search: String = "", remove: Bool = false) {
guard let storage = self.storage, search.count > 0 else { return }
let searchTerm = NSRegularExpression.escapedPattern(for: search)
let attributedString = NSMutableAttributedString(attributedString: storage)
let pattern = "(\(searchTerm))"
let range: NSRange = NSMakeRange(0, storage.length)
do {
let regex = try NSRegularExpression(pattern: pattern, options: [NSRegularExpression.Options.caseInsensitive])
regex.enumerateMatches(
in: storage.string,
options: NSRegularExpression.MatchingOptions(),
range: range,
using: {
(textCheckingResult, matchingFlags, stop) -> Void in
guard let subRange = textCheckingResult?.range else {
return
}
if remove {
if attributedString.attributes(at: subRange.location, effectiveRange: nil).keys.contains(NoteAttribute.highlight) {
storage.removeAttribute(NoteAttribute.highlight, range: subRange)
storage.addAttribute(NSAttributedString.Key.backgroundColor, value: NotesTextProcessor.codeBackground, range: subRange)
return
} else {
storage.removeAttribute(NSAttributedString.Key.backgroundColor, range: subRange)
}
} else {
if attributedString.attributes(at: subRange.location, effectiveRange: nil).keys.contains(NSAttributedString.Key.backgroundColor) {
attributedString.addAttribute(NoteAttribute.highlight, value: true, range: subRange)
}
attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: highlightColor, range: subRange)
}
}
)
if !remove {
storage.setAttributedString(attributedString)
}
} catch {
print(error)
}
}
}
public struct MarklightRegex {
public let regularExpression: NSRegularExpression!
public init(pattern: String, options: NSRegularExpression.Options = NSRegularExpression.Options(rawValue: 0)) {
var error: NSError?
let re: NSRegularExpression?
do {
re = try NSRegularExpression(pattern: pattern,
options: options)
} catch let error1 as NSError {
error = error1
re = nil
}
// If re is nil, it means NSRegularExpression didn't like
// the pattern we gave it. All regex patterns used by Markdown
// should be valid, so this probably means that a pattern
// valid for .NET Regex is not valid for NSRegularExpression.
if re == nil {
if let error = error {
print("Regular expression error: \(error.userInfo)")
}
assert(re != nil)
}
self.regularExpression = re
}
public func matches(_ input: String, range: NSRange,
completion: @escaping (_ result: NSTextCheckingResult?) -> Void) {
let s = input as NSString
//NSRegularExpression.
let options = NSRegularExpression.MatchingOptions(rawValue: 0)
regularExpression.enumerateMatches(in: s as String,
options: options,
range: range,
using: { (result, flags, stop) -> Void in
completion(result)
})
}
}
| [
-1
] |
28952fc7ed0ecda72a94f28edd60503516ed26fd | 1349da0337e42f397b02973ad3048e44ad0eae31 | /WatchNavigation WatchKit Extension/NotificationController.swift | d29d0847e716260437e5398df22d8895efe41ea6 | [] | no_license | Rajmaurya8085/WatchNavigation | eea342633f757e3902ab957eba576825c01fc6f1 | 0ec4bbf361c3be006cf88752b268400a91a031a6 | refs/heads/master | 2020-08-22T20:24:30.364047 | 2019-10-21T03:38:31 | 2019-10-21T03:38:31 | 216,471,694 | 0 | 0 | null | null | null | null | UTF-8 | Swift | false | false | 1,080 | swift | //
// NotificationController.swift
// WatchNavigation WatchKit Extension
//
// Created by Raunaque Quaiser on 21/10/19.
// Copyright © 2019 Rajmaurya_Personal_inc. All rights reserved.
//
import WatchKit
import Foundation
import UserNotifications
class NotificationController: WKUserNotificationInterfaceController {
override init() {
// Initialize variables here.
super.init()
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
override func didReceive(_ notification: UNNotification) {
// This method is called when a notification needs to be presented.
// Implement it if you use a dynamic notification interface.
// Populate your dynamic notification interface as quickly as possible.
}
}
| [
282371,
302728,
177290,
320538,
324762,
36767,
241443,
168101,
282405,
61868,
282413,
219696,
282420,
159034,
312892,
180044,
196688,
377682,
241500,
282332,
229221,
318445,
108910,
282351,
240116,
144501,
282360
] |
e1a06d200a701ff20851370d89aaf60f4bff13e2 | 90c65d2d689d42040ad59241333367c70c575b7e | /Sources/TMDBSwift/Client/Client.swift | c4b308f8cd37185dd246ba28632261a8187a1a88 | [
"MIT"
] | permissive | gkye/TheMovieDatabaseSwiftWrapper | 5068b49d383aa34cf269b7fe9869b47af6c3c466 | d9459c996942a54a9017b8e02e9bc60e698e452c | refs/heads/master | 2022-09-04T20:32:46.849884 | 2022-08-16T19:19:08 | 2022-08-16T19:19:08 | 51,860,004 | 156 | 61 | MIT | 2022-07-17T17:23:29 | 2016-02-16T18:53:30 | Swift | UTF-8 | Swift | false | false | 4,187 | swift | //
// Client.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-02-11.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public struct ClientReturn {
public var error: NSError?
public var data: Data?
}
public struct MDBReturn {
public var error: Error?
public var data: Data?
public var response: URLResponse?
init(err: Error?, data: Data?, reponse: URLResponse?) {
error = err
self.data = data
self.response = reponse
}
}
struct Client {
static func networkRequest(url: String, httpMethod: String = "GET", parameters: [String: AnyObject], completion: @escaping (ClientReturn) -> Void) {
var apiReturn = ClientReturn()
guard let apikey = TMDBConfig.apikey else {
fatalError("NO API is set. Set your api using TMDBConfig.api = YOURKEY")
}
var params = parameters
params["api_key"] = apikey as AnyObject
HTTPRequest.request(url, httpMethod: httpMethod, parameters: params) { (data, _, error) in
if let data = data {
apiReturn.data = data
}
apiReturn.error = error as NSError?
completion(apiReturn)
}
}
static func apiRequest(url: String, parameters: [String: AnyObject], completion: @escaping (MDBReturn) -> Void) {
HTTPRequest.request(url, parameters: parameters) { (data, response, error) in
let apiReturn = MDBReturn(err: error, data: data, reponse: response)
completion(apiReturn)
}
}
}
class HTTPRequest {
static func request(_ url: String, httpMethod: String = "GET", parameters: [String: AnyObject], completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
let parameterString = parameters.stringFromHttpParameters()
let urlString = url + "?" + parameterString
let requestURL = URL(string: urlString)!
let request = NSMutableURLRequest(url: requestURL)
request.httpMethod = httpMethod
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
DispatchQueue.main.async(execute: { () -> Void in
if error != nil {
completionHandler(nil, nil, error as Error?)
} else {
completionHandler(data, response, nil)
}
})
})
task.resume()
}
}
extension String {
/// Percent escapes values to be added to a URL query as specified in RFC 3986
///
/// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Returns percent-escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}
}
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = self.map { arr -> String in
let key = arr.key
let value = arr.value
let percentEscapedKey = (key as? String)?.stringByAddingPercentEncodingForURLQueryValue() ?? ""
let percentEscapedValue = (String(describing: value)).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joined(separator: "&")
}
}
| [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.