repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
patrick-sheehan/cwic
Source/EventSegmentsViewController.swift
1
1089
// // EventSegmentsViewController.swift // CWIC // // Created by Patrick Sheehan on 1/20/18. // Copyright © 2018 Síocháin Solutions. All rights reserved. // import SJSegmentedScrollView class EventSegmentsViewController { class var segments: [UITableViewController] { return [ // Starred StarredEventListViewController.generate(), // Trending TrendingEventListViewController.generate(), // All // UserStrangerListViewController.generate(), // Categorical // UserInvitesSentListViewController.generate(), ] } class func generate() -> UIViewController { let segmentView = SJSegmentedViewController(headerViewController: nil, segmentControllers: segments) segmentView.title = "Events" // segmentView.headerViewHeight = 0 // segmentView.headerViewOffsetHeight = 0 segmentView.selectedSegmentViewColor = .white segmentView.segmentBackgroundColor = Cwic.Blue segmentView.segmentTitleColor = .white segmentView.segmentTitleFont = Cwic.Font return segmentView } }
gpl-3.0
chrislzm/TimeAnalytics
Time Analytics/TAActivitySegment+CoreDataClass.swift
1
1382
// // TAActivitySegment+CoreDataClass.swift // Time Analytics // // Created by Chris Leung on 5/23/17. // Copyright © 2017 Chris Leung. All rights reserved. // import Foundation import CoreData @objc(TAActivitySegment) public class TAActivitySegment: NSManagedObject { // Transient property for grouping a table into sections based // on day of entity's date. Allows an NSFetchedResultsController // to sort by date, but also display the day as the section title. // - Constructs a string of format "YYYYMMDD", where YYYY is the year, // MM is the month, and DD is the day (all integers). // Credit: https://stackoverflow.com/a/42080729/7602403 public var daySectionIdentifier: String? { let currentCalendar = Calendar.current self.willAccessValue(forKey: "daySectionIdentifier") var sectionIdentifier = "" let date = self.startTime! as Date let day = currentCalendar.component(.day, from: date) let month = currentCalendar.component(.month, from: date) let year = currentCalendar.component(.year, from: date) // Construct integer from year, month, day. Convert to string. sectionIdentifier = "\(year * 10000 + month * 100 + day)" self.didAccessValue(forKey: "daySectionIdentifier") return sectionIdentifier } }
mit
TENDIGI/Obsidian-UI-iOS
src/Mutex.swift
1
1300
// // Mutex.swift // Alfredo // // Created by Nick Lee on 8/12/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation public struct MutexPool { fileprivate let semaphore: DispatchSemaphore // MARK: Initialization /** Creates a new MutexPool with an initial pool size. - parameter poolSize: The starting value of the MutexPool - returns: A newly instantiated MutexPool */ public init(poolSize: Int = 1) { semaphore = DispatchSemaphore(value: poolSize) } /** Waits for a resource in the pool to become available - parameter timeout: When to timeout (see dispatch_time). The constants DISPATCH_TIME_NOW and DISPATCH_TIME_FOREVER are available as a convenience. */ public func wait(_ timeout: DispatchTime = DispatchTime.distantFuture) { semaphore.wait(timeout: timeout) } /// Frees a used resource in the pool public func signal() { semaphore.signal() } /** Waits for resources to become available, performs the passed closure, and signals after it returns. - parameter closure: The closure to execute when a resource becomes available */ public func perform(_ closure: () -> ()) { wait() closure() signal() } }
mit
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Charts/RadarChartView.swift
7
7181
// // RadarChartView.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics /// Implementation of the RadarChart, a "spidernet"-like chart. It works best /// when displaying 5-10 entries per DataSet. open class RadarChartView: PieRadarChartViewBase { /// width of the web lines that come from the center. @objc open var webLineWidth = CGFloat(1.5) /// width of the web lines that are in between the lines coming from the center @objc open var innerWebLineWidth = CGFloat(0.75) /// color for the web lines that come from the center @objc open var webColor = NSUIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0) /// color for the web lines in between the lines that come from the center. @objc open var innerWebColor = NSUIColor(red: 122/255.0, green: 122/255.0, blue: 122.0/255.0, alpha: 1.0) /// transparency the grid is drawn with (0.0 - 1.0) @objc open var webAlpha: CGFloat = 150.0 / 255.0 /// flag indicating if the web lines should be drawn or not @objc open var drawWeb = true /// modulus that determines how many labels and web-lines are skipped before the next is drawn private var _skipWebLineCount = 0 /// the object reprsenting the y-axis labels private var _yAxis: YAxis! internal var _yAxisRenderer: YAxisRendererRadarChart! internal var _xAxisRenderer: XAxisRendererRadarChart! public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() _yAxis = YAxis(position: .left) renderer = RadarChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) _yAxisRenderer = YAxisRendererRadarChart(viewPortHandler: _viewPortHandler, yAxis: _yAxis, chart: self) _xAxisRenderer = XAxisRendererRadarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, chart: self) self.highlighter = RadarHighlighter(chart: self) } internal override func calcMinMax() { super.calcMinMax() guard let data = _data else { return } _yAxis.calculate(min: data.getYMin(axis: .left), max: data.getYMax(axis: .left)) _xAxis.calculate(min: 0.0, max: Double(data.maxEntryCountSet?.entryCount ?? 0)) } open override func notifyDataSetChanged() { calcMinMax() _yAxisRenderer?.computeAxis(min: _yAxis._axisMinimum, max: _yAxis._axisMaximum, inverted: _yAxis.isInverted) _xAxisRenderer?.computeAxis(min: _xAxis._axisMinimum, max: _xAxis._axisMaximum, inverted: false) if let data = _data, let legend = _legend, !legend.isLegendCustom { legendRenderer?.computeLegend(data: data) } calculateOffsets() setNeedsDisplay() } open override func draw(_ rect: CGRect) { super.draw(rect) guard data != nil, let renderer = renderer else { return } let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } if _xAxis.isEnabled { _xAxisRenderer.computeAxis(min: _xAxis._axisMinimum, max: _xAxis._axisMaximum, inverted: false) } _xAxisRenderer?.renderAxisLabels(context: context) if drawWeb { renderer.drawExtras(context: context) } if _yAxis.isEnabled && _yAxis.isDrawLimitLinesBehindDataEnabled { _yAxisRenderer.renderLimitLines(context: context) } renderer.drawData(context: context) if valuesToHighlight() { renderer.drawHighlighted(context: context, indices: _indicesToHighlight) } if _yAxis.isEnabled && !_yAxis.isDrawLimitLinesBehindDataEnabled { _yAxisRenderer.renderLimitLines(context: context) } _yAxisRenderer.renderAxisLabels(context: context) renderer.drawValues(context: context) legendRenderer.renderLegend(context: context) drawDescription(context: context) drawMarkers(context: context) } /// - returns: The factor that is needed to transform values into pixels. @objc open var factor: CGFloat { let content = _viewPortHandler.contentRect return min(content.width / 2.0, content.height / 2.0) / CGFloat(_yAxis.axisRange) } /// - returns: The angle that each slice in the radar chart occupies. @objc open var sliceAngle: CGFloat { return 360.0 / CGFloat(_data?.maxEntryCountSet?.entryCount ?? 0) } open override func indexForAngle(_ angle: CGFloat) -> Int { // take the current angle of the chart into consideration let a = (angle - self.rotationAngle).normalizedAngle let sliceAngle = self.sliceAngle let max = _data?.maxEntryCountSet?.entryCount ?? 0 var index = 0 for i in 0..<max { let referenceAngle = sliceAngle * CGFloat(i + 1) - sliceAngle / 2.0 if referenceAngle > a { index = i break } } return index } /// - returns: The object that represents all y-labels of the RadarChart. @objc open var yAxis: YAxis { return _yAxis } /// Sets the number of web-lines that should be skipped on chart web before the next one is drawn. This targets the lines that come from the center of the RadarChart. /// if count = 1 -> 1 line is skipped in between @objc open var skipWebLineCount: Int { get { return _skipWebLineCount } set { _skipWebLineCount = max(0, newValue) } } internal override var requiredLegendOffset: CGFloat { return _legend.font.pointSize * 4.0 } internal override var requiredBaseOffset: CGFloat { return _xAxis.isEnabled && _xAxis.isDrawLabelsEnabled ? _xAxis.labelRotatedWidth : 10.0 } open override var radius: CGFloat { let content = _viewPortHandler.contentRect return min(content.width / 2.0, content.height / 2.0) } /// - returns: The maximum value this chart can display on it's y-axis. open override var chartYMax: Double { return _yAxis._axisMaximum } /// - returns: The minimum value this chart can display on it's y-axis. open override var chartYMin: Double { return _yAxis._axisMinimum } /// - returns: The range of y-values this chart can display. @objc open var yRange: Double { return _yAxis.axisRange } }
apache-2.0
K-cat/CatMediaPickerController
Example-iOS/AppDelegate.swift
1
2168
// // AppDelegate.swift // Example-iOS // // Created by Kcat on 2018/3/21. // Copyright © 2018年 ImKcat. 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:. } }
mit
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Extensions/RealmExecute.swift
1
3203
// // RealmExecute.swift // Rocket.Chat // // Created by Matheus Cardoso on 3/1/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import RealmSwift extension Realm { static let writeQueue = DispatchQueue(label: "chat.rocket.realm.write", qos: .background) #if TEST func execute(_ execution: @escaping (Realm) -> Void, completion: VoidCompletion? = nil) { if isInWriteTransaction { execution(self) } else { try? write { execution(self) } } completion?() } #endif #if !TEST func execute(_ execution: @escaping (Realm) -> Void, completion: VoidCompletion? = nil) { var backgroundTaskId: UIBackgroundTaskIdentifier? backgroundTaskId = UIApplication.shared.beginBackgroundTask(withName: "chat.rocket.realm.background") { backgroundTaskId = UIBackgroundTaskIdentifier.invalid } if let backgroundTaskId = backgroundTaskId { let config = self.configuration Realm.writeQueue.async { if let realm = try? Realm(configuration: config) { try? realm.write { execution(realm) } } if let completion = completion { DispatchQueue.main.async { completion() } } UIApplication.shared.endBackgroundTask(backgroundTaskId) } } } #endif static func execute(_ execution: @escaping (Realm) -> Void, completion: VoidCompletion? = nil) { Realm.current?.execute(execution, completion: completion) } static func executeOnMainThread(realm: Realm? = nil, _ execution: @escaping (Realm) -> Void) { if let realm = realm { if realm.isInWriteTransaction { execution(realm) } else { try? realm.write { execution(realm) } } return } guard let currentRealm = Realm.current else { return } if currentRealm.isInWriteTransaction { execution(currentRealm) } else { try? currentRealm.write { execution(currentRealm) } } } #if TEST static func clearDatabase() { Realm.execute({ realm in realm.deleteAll() }) } #endif // MARK: Mutate // This method will add or update a Realm's object. static func delete(_ object: Object) { guard !object.isInvalidated else { return } self.execute({ realm in realm.delete(object) }) } // This method will add or update a Realm's object. static func update(_ object: Object) { self.execute({ realm in realm.add(object, update: true) }) } // This method will add or update a list of some Realm's object. static func update<S: Sequence>(_ objects: S) where S.Iterator.Element: Object { self.execute({ realm in realm.add(objects, update: true) }) } }
mit
emilstahl/swift
validation-test/compiler_crashers_fixed/1844-swift-constraints-constraintsystem-assignfixedtype.swift
13
388
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A, Any) -> { } print(A? { } func g<T: A { protocol a { func b) -> Bool { extension NSSet { } class A { } } var d where g: H.init() -> { } protocol b : a { func a(b()
apache-2.0
shadanan/mado
Antlr4Runtime/Sources/Antlr4/tree/ParseTreeVisitor.swift
1
2058
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /** * This interface defines the basic notion of a parse tree visitor. Generated * visitors implement this interface and the {@code XVisitor} interface for * grammar {@code X}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ open class ParseTreeVisitor<T> { public init() { } // typealias T /** * Visit a parse tree, and return a user-defined result of the operation. * * @param tree The {@link org.antlr.v4.runtime.tree.ParseTree} to visit. * @return The result of visiting the parse tree. */ open func visit(_ tree: ParseTree) -> T? { RuntimeException(" must overriden !") return nil } /** * Visit the children of a node, and return a user-defined result of the * operation. * * @param node The {@link org.antlr.v4.runtime.tree.RuleNode} whose children should be visited. * @return The result of visiting the children of the node. */ open func visitChildren(_ node: RuleNode) -> T? { RuntimeException(" must overriden !") return nil } /** * Visit a terminal node, and return a user-defined result of the operation. * * @param node The {@link org.antlr.v4.runtime.tree.TerminalNode} to visit. * @return The result of visiting the node. */ open func visitTerminal(_ node: TerminalNode) -> T? { RuntimeException(" must overriden !") return nil } /** * Visit an error node, and return a user-defined result of the operation. * * @param node The {@link org.antlr.v4.runtime.tree.ErrorNode} to visit. * @return The result of visiting the node. */ open func visitErrorNode(_ node: ErrorNode) -> T? { RuntimeException(" must overriden !") return nil } }
mit
coreyjv/Emby.ApiClient.Swift
Emby.ApiClient/model/system/SystemInfo.swift
2
3047
// // SystemInfo.swift // Emby.ApiClient // import Foundation public class SystemInfo: PublicSystemInfo { let operatingSystemDisplayName: String let isRunningAsService: Bool let supportsRunningAsService: Bool let macAddress: String let hasPendingRestart: Bool let supportsSync: Bool let isNetworkDeployed: Bool let inProgressInstallations: [InstallationInfo] let webSocketPortNumber: Int let completedInstallations: [InstallationInfo] let canSelfRestart: Bool let canSelfUpdate: Bool let failedPluginAssemblies: [String] let programDataPath: String let itemsByNamePath: String let cachePath: String let logPath: String let transcodingTempPath: String let httpServerPortNumber: Int let supportsHttps: Bool let hasUpdatesAvailable: Bool let supportsAutoRunAtStartup: Bool init(localAddress: String?, wanAddress: String?, serverName: String, version: String, operatingSystem: String, id: String, operatingSystemDisplayName: String, isRunningAsService: Bool, supportsRunningAsService: Bool, macAddress: String, hasPendingRestart: Bool, supportsSync: Bool, isNetworkDeployed: Bool,inProgressInstallations: [InstallationInfo], webSocketPortNumber: Int, completedInstallations: [InstallationInfo], canSelfRestart: Bool, canSelfUpdate: Bool, failedPluginAssemblies: [String], programDataPath: String, itemsByNamePath: String, cachePath: String, logPath: String, transcodingTempPath: String, httpServerPortNumber: Int, supportsHttps: Bool, hasUpdatesAvailable: Bool, supportsAutoRunAtStartup: Bool) { self.operatingSystemDisplayName = operatingSystemDisplayName self.isRunningAsService = isRunningAsService self.supportsRunningAsService = supportsRunningAsService self.macAddress = macAddress self.hasPendingRestart = hasPendingRestart self.supportsSync = supportsSync self.isNetworkDeployed = isNetworkDeployed self.inProgressInstallations = inProgressInstallations self.webSocketPortNumber = webSocketPortNumber self.completedInstallations = completedInstallations self.canSelfRestart = canSelfRestart self.canSelfUpdate = canSelfUpdate self.failedPluginAssemblies = failedPluginAssemblies self.programDataPath = programDataPath self.itemsByNamePath = itemsByNamePath self.cachePath = cachePath self.logPath = logPath self.transcodingTempPath = transcodingTempPath self.httpServerPortNumber = httpServerPortNumber self.supportsHttps = supportsHttps self.hasUpdatesAvailable = hasUpdatesAvailable self.supportsAutoRunAtStartup = supportsAutoRunAtStartup super.init(localAddress: localAddress, wanAddress: wanAddress, serverName: serverName, version: version, operatingSystem: operatingSystem, id: id) } // TODO: Handle JSON public required init?(jSON: JSON_Object) { fatalError("init(jSON:) has not been implemented: \(jSON)") } }
mit
josve05a/wikipedia-ios
Wikipedia/Code/ExploreViewController.swift
2
42615
import UIKit import WMF class ExploreViewController: ColumnarCollectionViewController, ExploreCardViewControllerDelegate, UISearchBarDelegate, CollectionViewUpdaterDelegate, ImageScaleTransitionProviding, DetailTransitionSourceProviding, EventLoggingEventValuesProviding { public var presentedContentGroupKey: String? public var shouldRestoreScrollPosition = false // MARK - UIViewController override func viewDidLoad() { super.viewDidLoad() layoutManager.register(ExploreCardCollectionViewCell.self, forCellWithReuseIdentifier: ExploreCardCollectionViewCell.identifier, addPlaceholder: true) navigationItem.titleView = titleView navigationBar.addUnderNavigationBarView(searchBarContainerView) navigationBar.isUnderBarViewHidingEnabled = true navigationBar.displayType = .largeTitle navigationBar.shouldTransformUnderBarViewWithBar = true navigationBar.isShadowHidingEnabled = true isRefreshControlEnabled = true collectionView.refreshControl?.layer.zPosition = 0 title = CommonStrings.exploreTabTitle NotificationCenter.default.addObserver(self, selector: #selector(exploreFeedPreferencesDidSave(_:)), name: NSNotification.Name.WMFExploreFeedPreferencesDidSave, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(articleDidChange(_:)), name: NSNotification.Name.WMFArticleUpdated, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(articleDeleted(_:)), name: NSNotification.Name.WMFArticleDeleted, object: nil) #if UI_TEST if UserDefaults.standard.wmf_isFastlaneSnapshotInProgress() { collectionView.decelerationRate = .fast } #endif } deinit { NotificationCenter.default.removeObserver(self) NSObject.cancelPreviousPerformRequests(withTarget: self) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) startMonitoringReachabilityIfNeeded() showOfflineEmptyViewIfNeeded() imageScaleTransitionView = nil detailTransitionSourceRect = nil logFeedImpressionAfterDelay() } override func viewWillHaveFirstAppearance(_ animated: Bool) { super.viewWillHaveFirstAppearance(animated) setupFetchedResultsController() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) collectionViewUpdater?.isGranularUpdatingEnabled = true restoreScrollPositionIfNeeded() } private func restoreScrollPositionIfNeeded() { guard shouldRestoreScrollPosition, let presentedContentGroupKey = presentedContentGroupKey, let contentGroup = fetchedResultsController?.fetchedObjects?.first(where: { $0.key == presentedContentGroupKey }), let indexPath = fetchedResultsController?.indexPath(forObject: contentGroup) else { return } collectionView.scrollToItem(at: indexPath, at: [], animated: false) self.shouldRestoreScrollPosition = false self.presentedContentGroupKey = nil } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) dataStore.feedContentController.dismissCollapsedContentGroups() stopMonitoringReachability() collectionViewUpdater?.isGranularUpdatingEnabled = false } // MARK - NavBar @objc func titleBarButtonPressed(_ sender: UIButton?) { scrollToTop() } @objc public var titleButton: UIView { return titleView } lazy var longTitleButton: UIButton = { let longTitleButton = UIButton(type: .custom) longTitleButton.adjustsImageWhenHighlighted = true longTitleButton.setImage(UIImage(named: "wikipedia"), for: .normal) longTitleButton.sizeToFit() longTitleButton.addTarget(self, action: #selector(titleBarButtonPressed), for: .touchUpInside) longTitleButton.isAccessibilityElement = false return longTitleButton }() lazy var titleView: UIView = { let titleView = UIView(frame: longTitleButton.bounds) titleView.addSubview(longTitleButton) titleView.isAccessibilityElement = false return titleView }() // MARK - Refresh open override func refresh() { FeedFunnel.shared.logFeedRefreshed() updateFeedSources(with: nil, userInitiated: true) { } } // MARK - Scroll var isLoadingOlderContent: Bool = false override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) guard !isLoadingOlderContent else { return } let ratio: CGFloat = scrollView.contentOffset.y / (scrollView.contentSize.height - scrollView.bounds.size.height) if ratio < 0.8 { return } let lastSectionIndex = numberOfSectionsInExploreFeed - 1 guard lastSectionIndex >= 0 else { return } let lastItemIndex = numberOfItemsInSection(lastSectionIndex) - 1 guard lastItemIndex >= 0 else { return } guard let lastGroup = group(at: IndexPath(item: lastItemIndex, section: lastSectionIndex)) else { return } let now = Date() let midnightUTC: Date = (now as NSDate).wmf_midnightUTCDateFromLocal guard let lastGroupMidnightUTC = lastGroup.midnightUTCDate else { return } let calendar = NSCalendar.wmf_gregorian() let days: Int = calendar?.wmf_days(from: lastGroupMidnightUTC, to: midnightUTC) ?? 0 guard days < Int(WMFExploreFeedMaximumNumberOfDays) else { return } guard let nextOldestDate: Date = calendar?.date(byAdding: .day, value: -1, to: lastGroupMidnightUTC, options: .matchStrictly) else { return } isLoadingOlderContent = true FeedFunnel.shared.logFeedRefreshed() updateFeedSources(with: (nextOldestDate as NSDate).wmf_midnightLocalDateForEquivalentUTC, userInitiated: false) { self.isLoadingOlderContent = false } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { logFeedImpressionAfterDelay() } // MARK: - Event logging private func logFeedImpressionAfterDelay() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(logFeedImpression), object: nil) perform(#selector(logFeedImpression), with: self, afterDelay: 3) } @objc private func logFeedImpression() { for indexPath in collectionView.indexPathsForVisibleItems { guard let group = group(at: indexPath), group.undoType == .none, let itemFrame = collectionView.layoutAttributesForItem(at: indexPath)?.frame else { continue } let visibleRectOrigin = CGPoint(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y + navigationBar.visibleHeight) let visibleRectSize = view.layoutMarginsGuide.layoutFrame.size let itemCenter = CGPoint(x: itemFrame.midX, y: itemFrame.midY) let visibleRect = CGRect(origin: visibleRectOrigin, size: visibleRectSize) let isUnobstructed = visibleRect.contains(itemCenter) guard isUnobstructed else { continue } FeedFunnel.shared.logFeedImpression(for: FeedFunnelContext(group)) } } // MARK - Search public var wantsCustomSearchTransition: Bool { return true } lazy var searchBarContainerView: UIView = { let searchContainerView = UIView() searchBar.translatesAutoresizingMaskIntoConstraints = false searchContainerView.addSubview(searchBar) let leading = searchContainerView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: searchBar.leadingAnchor) let trailing = searchContainerView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: searchBar.trailingAnchor) let top = searchContainerView.topAnchor.constraint(equalTo: searchBar.topAnchor) let bottom = searchContainerView.bottomAnchor.constraint(equalTo: searchBar.bottomAnchor) searchContainerView.addConstraints([leading, trailing, top, bottom]) return searchContainerView }() lazy var searchBar: UISearchBar = { let searchBar = UISearchBar() searchBar.delegate = self searchBar.returnKeyType = .search searchBar.searchBarStyle = .minimal searchBar.placeholder = WMFLocalizedString("search-field-placeholder-text", value: "Search Wikipedia", comment: "Search field placeholder text") return searchBar }() @objc func ensureWikipediaSearchIsShowing() { if self.navigationBar.underBarViewPercentHidden > 0 { self.navigationBar.setNavigationBarPercentHidden(0, underBarViewPercentHidden: 0, extendedViewPercentHidden: 0, topSpacingPercentHidden: 1, animated: true) } } // MARK - UISearchBarDelegate func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { let searchActivity = NSUserActivity.wmf_searchView() NotificationCenter.default.post(name: .WMFNavigateToActivity, object: searchActivity) return false } // MARK - State @objc var dataStore: MWKDataStore! private var fetchedResultsController: NSFetchedResultsController<WMFContentGroup>? private var collectionViewUpdater: CollectionViewUpdater<WMFContentGroup>? private var wantsDeleteInsertOnNextItemUpdate: Bool = false private func setupFetchedResultsController() { let fetchRequest: NSFetchRequest<WMFContentGroup> = WMFContentGroup.fetchRequest() fetchRequest.predicate = NSPredicate(format: "isVisible == YES && (placement == NULL || placement == %@)", "feed") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "midnightUTCDate", ascending: false), NSSortDescriptor(key: "dailySortPriority", ascending: true), NSSortDescriptor(key: "date", ascending: false)] let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: dataStore.viewContext, sectionNameKeyPath: "midnightUTCDate", cacheName: nil) fetchedResultsController = frc let updater = CollectionViewUpdater(fetchedResultsController: frc, collectionView: collectionView) collectionViewUpdater = updater updater.delegate = self updater.isSlidingNewContentInFromTheTopEnabled = true updater.performFetch() } private func group(at indexPath: IndexPath) -> WMFContentGroup? { guard let frc = fetchedResultsController, frc.isValidIndexPath(indexPath) else { return nil } return frc.object(at: indexPath) } private func groupKey(at indexPath: IndexPath) -> String? { return group(at: indexPath)?.key } lazy var saveButtonsController: SaveButtonsController = { let sbc = SaveButtonsController(dataStore: dataStore) sbc.delegate = self return sbc }() var numberOfSectionsInExploreFeed: Int { guard let sections = fetchedResultsController?.sections else { return 0 } return sections.count } func numberOfItemsInSection(_ section: Int) -> Int { guard let sections = fetchedResultsController?.sections, sections.count > section else { return 0 } return sections[section].numberOfObjects } override func numberOfSections(in collectionView: UICollectionView) -> Int { return numberOfSectionsInExploreFeed } private func resetRefreshControl() { guard let refreshControl = collectionView.refreshControl, refreshControl.isRefreshing else { return } refreshControl.endRefreshing() } lazy var reachabilityNotifier: ReachabilityNotifier = { let notifier = ReachabilityNotifier(Configuration.current.defaultSiteDomain) { [weak self] (reachable, flags) in if reachable { DispatchQueue.main.async { self?.updateFeedSources(userInitiated: false) } } else { DispatchQueue.main.async { self?.showOfflineEmptyViewIfNeeded() } } } return notifier }() private func stopMonitoringReachability() { reachabilityNotifier.stop() } private func startMonitoringReachabilityIfNeeded() { guard numberOfSectionsInExploreFeed == 0 else { stopMonitoringReachability() return } reachabilityNotifier.start() } private func showOfflineEmptyViewIfNeeded() { guard isViewLoaded && fetchedResultsController != nil else { return } guard numberOfSectionsInExploreFeed == 0 else { wmf_hideEmptyView() return } guard !wmf_isShowingEmptyView() else { return } guard !reachabilityNotifier.isReachable else { return } resetRefreshControl() wmf_showEmptyView(of: .noFeed, theme: theme, frame: view.bounds) } var isLoadingNewContent = false @objc(updateFeedSourcesWithDate:userInitiated:completion:) public func updateFeedSources(with date: Date? = nil, userInitiated: Bool, completion: @escaping () -> Void = { }) { assert(Thread.isMainThread) guard !isLoadingNewContent else { completion() return } isLoadingNewContent = true if date == nil, let refreshControl = collectionView.refreshControl, !refreshControl.isRefreshing { #if UI_TEST #else refreshControl.beginRefreshing() #endif if numberOfSectionsInExploreFeed == 0 { scrollToTop() } } self.dataStore.feedContentController.updateFeedSources(with: date, userInitiated: userInitiated) { DispatchQueue.main.async { self.isLoadingNewContent = false self.resetRefreshControl() if date == nil { self.startMonitoringReachabilityIfNeeded() self.showOfflineEmptyViewIfNeeded() } completion() } } } override func contentSizeCategoryDidChange(_ notification: Notification?) { layoutCache.reset() super.contentSizeCategoryDidChange(notification) } // MARK - ImageScaleTransitionProviding var imageScaleTransitionView: UIImageView? // MARK - DetailTransitionSourceProviding var detailTransitionSourceRect: CGRect? // MARK - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfItemsInSection(section) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let maybeCell = collectionView.dequeueReusableCell(withReuseIdentifier: ExploreCardCollectionViewCell.identifier, for: indexPath) guard let cell = maybeCell as? ExploreCardCollectionViewCell else { return maybeCell } cell.apply(theme: theme) configure(cell: cell, forItemAt: indexPath, layoutOnly: false) return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard kind == UICollectionView.elementKindSectionHeader else { abort() } guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CollectionViewHeader.identifier, for: indexPath) as? CollectionViewHeader else { abort() } configureHeader(header, for: indexPath.section) return header } // MARK - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { guard let group = group(at: indexPath) else { return false } return group.isSelectable } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell { detailTransitionSourceRect = view.convert(cell.frame, from: collectionView) if let vc = cell.cardContent as? ExploreCardViewController, vc.collectionView.numberOfSections > 0, vc.collectionView.numberOfItems(inSection: 0) > 0, let cell = vc.collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) as? ArticleCollectionViewCell { imageScaleTransitionView = cell.imageView.isHidden ? nil : cell.imageView } else { imageScaleTransitionView = nil } } guard let group = group(at: indexPath) else { return } presentedContentGroupKey = group.key if let vc = group.detailViewControllerWithDataStore(dataStore, theme: theme) { wmf_push(vc, context: FeedFunnelContext(group), index: indexPath.item, animated: true) return } if let vc = group.detailViewControllerForPreviewItemAtIndex(0, dataStore: dataStore, theme: theme) { if vc is WMFImageGalleryViewController { present(vc, animated: true) FeedFunnel.shared.logFeedCardOpened(for: FeedFunnelContext(group)) } else { wmf_push(vc, context: FeedFunnelContext(group), index: indexPath.item, animated: true) } return } } func configureHeader(_ header: CollectionViewHeader, for sectionIndex: Int) { guard collectionView(collectionView, numberOfItemsInSection: sectionIndex) > 0 else { return } guard let group = group(at: IndexPath(item: 0, section: sectionIndex)) else { return } header.title = (group.midnightUTCDate as NSDate?)?.wmf_localizedRelativeDateFromMidnightUTCDate() header.apply(theme: theme) } func createNewCardVCFor(_ cell: ExploreCardCollectionViewCell) -> ExploreCardViewController { let cardVC = ExploreCardViewController() cardVC.delegate = self cardVC.dataStore = dataStore cardVC.view.autoresizingMask = [] addChild(cardVC) cell.cardContent = cardVC cardVC.didMove(toParent: self) return cardVC } func configure(cell: ExploreCardCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) { let cardVC = cell.cardContent as? ExploreCardViewController ?? createNewCardVCFor(cell) guard let group = group(at: indexPath) else { return } cardVC.contentGroup = group cell.title = group.headerTitle cell.subtitle = group.headerSubTitle cell.footerTitle = cardVC.footerText cell.isCustomizationButtonHidden = !(group.contentGroupKind.isCustomizable || group.contentGroupKind.isGlobal) cell.undoType = group.undoType cell.apply(theme: theme) cell.delegate = self if group.undoType == .contentGroupKind { indexPathsForCollapsedCellsThatCanReappear.insert(indexPath) } } override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } searchBar.apply(theme: theme) searchBarContainerView.backgroundColor = theme.colors.paperBackground collectionView.backgroundColor = .clear view.backgroundColor = theme.colors.paperBackground for cell in collectionView.visibleCells { guard let themeable = cell as? Themeable else { continue } themeable.apply(theme: theme) } for header in collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader) { guard let themeable = header as? Themeable else { continue } themeable.apply(theme: theme) } } // MARK: - ColumnarCollectionViewLayoutDelegate override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate { guard let group = group(at: indexPath) else { return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0) } let identifier = ExploreCardCollectionViewCell.identifier let userInfo = "evc-cell-\(group.key ?? "")" if let cachedHeight = layoutCache.cachedHeightForCellWithIdentifier(identifier, columnWidth: columnWidth, userInfo: userInfo) { return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: cachedHeight) } var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 100) guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: ExploreCardCollectionViewCell.identifier) as? ExploreCardCollectionViewCell else { return estimate } configure(cell: placeholderCell, forItemAt: indexPath, layoutOnly: true) estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height estimate.precalculated = true layoutCache.setHeight(estimate.height, forCellWithIdentifier: identifier, columnWidth: columnWidth, groupKey: group.key, userInfo: userInfo) return estimate } override func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate { guard let group = self.group(at: IndexPath(item: 0, section: section)), let date = group.midnightUTCDate, date < Date() else { return ColumnarCollectionViewLayoutHeightEstimate(precalculated: true, height: 0) } var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 100) guard let header = layoutManager.placeholder(forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: CollectionViewHeader.identifier) as? CollectionViewHeader else { return estimate } configureHeader(header, for: section) estimate.height = header.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height estimate.precalculated = true return estimate } override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics { return ColumnarCollectionViewLayoutMetrics.exploreViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins) } override func collectionView(_ collectionView: UICollectionView, shouldShowFooterForSection section: Int) -> Bool { return false } // MARK - ExploreCardViewControllerDelegate func exploreCardViewController(_ exploreCardViewController: ExploreCardViewController, didSelectItemAtIndexPath indexPath: IndexPath) { guard let contentGroup = exploreCardViewController.contentGroup, let vc = contentGroup.detailViewControllerForPreviewItemAtIndex(indexPath.row, dataStore: dataStore, theme: theme) else { return } if let cell = exploreCardViewController.collectionView.cellForItem(at: indexPath) { detailTransitionSourceRect = view.convert(cell.frame, from: exploreCardViewController.collectionView) if let articleCell = cell as? ArticleCollectionViewCell, !articleCell.imageView.isHidden { imageScaleTransitionView = articleCell.imageView } else { imageScaleTransitionView = nil } } if let otdvc = vc as? OnThisDayViewController { otdvc.initialEvent = (contentGroup.contentPreview as? [Any])?[indexPath.item] as? WMFFeedOnThisDayEvent } let context = FeedFunnelContext(contentGroup) presentedContentGroupKey = contentGroup.key switch contentGroup.detailType { case .gallery: present(vc, animated: true) FeedFunnel.shared.logFeedCardOpened(for: context) default: wmf_push(vc, context: context, index: indexPath.item, animated: true) } } // MARK - Prefetching override func imageURLsForItemAt(_ indexPath: IndexPath) -> Set<URL>? { guard let contentGroup = group(at: indexPath) else { return nil } return contentGroup.imageURLsCompatibleWithTraitCollection(traitCollection, dataStore: dataStore) } #if DEBUG override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { guard motion == .motionShake else { return } dataStore.feedContentController.debugChaos() } #endif // MARK - CollectionViewUpdaterDelegate var needsReloadVisibleCells = false var indexPathsForCollapsedCellsThatCanReappear = Set<IndexPath>() private func reloadVisibleCells() { for indexPath in collectionView.indexPathsForVisibleItems { guard let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell else { continue } configure(cell: cell, forItemAt: indexPath, layoutOnly: false) } } func collectionViewUpdater<T: NSFetchRequestResult>(_ updater: CollectionViewUpdater<T>, didUpdate collectionView: UICollectionView) { guard needsReloadVisibleCells else { return } reloadVisibleCells() needsReloadVisibleCells = false layout.currentSection = nil } func collectionViewUpdater<T: NSFetchRequestResult>(_ updater: CollectionViewUpdater<T>, updateItemAtIndexPath indexPath: IndexPath, in collectionView: UICollectionView) { layoutCache.invalidateGroupKey(groupKey(at: indexPath)) collectionView.collectionViewLayout.invalidateLayout() if wantsDeleteInsertOnNextItemUpdate { layout.currentSection = indexPath.section collectionView.deleteItems(at: [indexPath]) collectionView.insertItems(at: [indexPath]) } else { needsReloadVisibleCells = true } } // MARK: Event logging var eventLoggingCategory: EventLoggingCategory { return .feed } var eventLoggingLabel: EventLoggingLabel? { return previewed.context?.label } // MARK: Peek & Pop private var previewed: (context: FeedFunnelContext?, indexPath: IndexPath?) override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = collectionViewIndexPathForPreviewingContext(previewingContext, location: location), let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell, let vc = cell.cardContent as? ExploreCardViewController, let contentGroup = vc.contentGroup else { return nil } previewed.context = FeedFunnelContext(contentGroup) let convertedLocation = view.convert(location, to: vc.collectionView) if let indexPath = vc.collectionView.indexPathForItem(at: convertedLocation), let cell = vc.collectionView.cellForItem(at: indexPath), let viewControllerToCommit = contentGroup.detailViewControllerForPreviewItemAtIndex(indexPath.row, dataStore: dataStore, theme: theme) { previewingContext.sourceRect = view.convert(cell.bounds, from: cell) if let potd = viewControllerToCommit as? WMFImageGalleryViewController { potd.setOverlayViewTopBarHidden(true) } else if let avc = viewControllerToCommit as? WMFArticleViewController { avc.articlePreviewingActionsDelegate = self avc.wmf_addPeekableChildViewController(for: avc.articleURL, dataStore: dataStore, theme: theme) } previewed.indexPath = indexPath FeedFunnel.shared.logFeedCardPreviewed(for: previewed.context, index: indexPath.item) return viewControllerToCommit } else if contentGroup.contentGroupKind != .random { return contentGroup.detailViewControllerWithDataStore(dataStore, theme: theme) } else { return nil } } open override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { if let potd = viewControllerToCommit as? WMFImageGalleryViewController { potd.setOverlayViewTopBarHidden(false) present(potd, animated: false) FeedFunnel.shared.logFeedCardOpened(for: previewed.context) } else if let avc = viewControllerToCommit as? WMFArticleViewController { avc.wmf_removePeekableChildViewControllers() wmf_push(avc, context: previewed.context, index: previewed.indexPath?.item, animated: false) } else { wmf_push(viewControllerToCommit, context: previewed.context, index: previewed.indexPath?.item, animated: true) } } // MARK: var addArticlesToReadingListVCDidDisappear: (() -> Void)? = nil } // MARK - Analytics extension ExploreViewController { private func logArticleSavedStateChange(_ wasArticleSaved: Bool, saveButton: SaveButton?, article: WMFArticle, userInfo: Any?) { guard let articleURL = article.url else { assert(false, "Article missing url: \(article)") return } guard let userInfo = userInfo as? ExploreSaveButtonUserInfo, let midnightUTCDate = userInfo.midnightUTCDate, let kind = userInfo.kind else { assert(false, "Article missing user info: \(article)") return } let index = userInfo.indexPath.item if wasArticleSaved { ReadingListsFunnel.shared.logSaveInFeed(saveButton: saveButton, articleURL: articleURL, kind: kind, index: index, date: midnightUTCDate) } else { ReadingListsFunnel.shared.logUnsaveInFeed(saveButton: saveButton, articleURL: articleURL, kind: kind, index: index, date: midnightUTCDate) } } } extension ExploreViewController: SaveButtonsControllerDelegate { func didSaveArticle(_ saveButton: SaveButton?, didSave: Bool, article: WMFArticle, userInfo: Any?) { let logSavedEvent = { self.logArticleSavedStateChange(didSave, saveButton: saveButton, article: article, userInfo: userInfo) } if isPresentingAddArticlesToReadingListVC() { addArticlesToReadingListVCDidDisappear = logSavedEvent } else { logSavedEvent() } } func willUnsaveArticle(_ article: WMFArticle, userInfo: Any?) { if article.userCreatedReadingListsCount > 0 { let alertController = ReadingListsAlertController() alertController.showAlert(presenter: self, article: article) } else { saveButtonsController.updateSavedState() } } func showAddArticlesToReadingListViewController(for article: WMFArticle) { let addArticlesToReadingListViewController = AddArticlesToReadingListViewController(with: dataStore, articles: [article], moveFromReadingList: nil, theme: theme) addArticlesToReadingListViewController.delegate = self let navigationController = WMFThemeableNavigationController(rootViewController: addArticlesToReadingListViewController, theme: self.theme) navigationController.isNavigationBarHidden = true present(navigationController, animated: true) } private func isPresentingAddArticlesToReadingListVC() -> Bool { guard let navigationController = presentedViewController as? UINavigationController else { return false } return navigationController.viewControllers.contains { $0 is AddArticlesToReadingListViewController } } } extension ExploreViewController: AddArticlesToReadingListDelegate { func addArticlesToReadingListWillClose(_ addArticlesToReadingList: AddArticlesToReadingListViewController) { } func addArticlesToReadingListDidDisappear(_ addArticlesToReadingList: AddArticlesToReadingListViewController) { addArticlesToReadingListVCDidDisappear?() addArticlesToReadingListVCDidDisappear = nil } func addArticlesToReadingList(_ addArticlesToReadingList: AddArticlesToReadingListViewController, didAddArticles articles: [WMFArticle], to readingList: ReadingList) { } } extension ExploreViewController: ReadingListsAlertControllerDelegate { func readingListsAlertController(_ readingListsAlertController: ReadingListsAlertController, didSelectUnsaveForArticle: WMFArticle) { saveButtonsController.updateSavedState() } } extension ExploreViewController: ExploreCardCollectionViewCellDelegate { func exploreCardCollectionViewCellWantsCustomization(_ cell: ExploreCardCollectionViewCell) { guard let vc = cell.cardContent as? ExploreCardViewController, let group = vc.contentGroup else { return } guard let sheet = menuActionSheetForGroup(group) else { return } sheet.popoverPresentationController?.sourceView = cell.customizationButton sheet.popoverPresentationController?.sourceRect = cell.customizationButton.bounds present(sheet, animated: true) } private func save() { do { try self.dataStore.save() } catch let error { DDLogError("Error saving after cell customization update: \(error)") } } @objc func exploreFeedPreferencesDidSave(_ note: Notification) { DispatchQueue.main.async { for indexPath in self.indexPathsForCollapsedCellsThatCanReappear { guard self.fetchedResultsController?.isValidIndexPath(indexPath) ?? false else { continue } self.layoutCache.invalidateGroupKey(self.groupKey(at: indexPath)) self.collectionView.collectionViewLayout.invalidateLayout() } self.indexPathsForCollapsedCellsThatCanReappear = [] } } @objc func articleDidChange(_ note: Notification) { guard let article = note.object as? WMFArticle, let articleKey = article.key else { return } var needsReload = false if article.hasChangedValuesForCurrentEventThatAffectPreviews, layoutCache.invalidateArticleKey(articleKey) { needsReload = true collectionView.collectionViewLayout.invalidateLayout() } else if !article.hasChangedValuesForCurrentEventThatAffectSavedState { return } let visibleIndexPathsWithChanges = collectionView.indexPathsForVisibleItems.filter { (indexPath) -> Bool in guard let contentGroup = group(at: indexPath) else { return false } return contentGroup.previewArticleKeys.contains(articleKey) } guard !visibleIndexPathsWithChanges.isEmpty else { return } for indexPath in visibleIndexPathsWithChanges { guard let cell = collectionView.cellForItem(at: indexPath) as? ExploreCardCollectionViewCell else { continue } if needsReload { configure(cell: cell, forItemAt: indexPath, layoutOnly: false) } else if let cardVC = cell.cardContent as? ExploreCardViewController { cardVC.savedStateDidChangeForArticleWithKey(articleKey) } } } @objc func articleDeleted(_ note: Notification) { guard let articleKey = note.userInfo?[WMFArticleDeletedNotificationUserInfoArticleKeyKey] as? String else { return } layoutCache.invalidateArticleKey(articleKey) } private func menuActionSheetForGroup(_ group: WMFContentGroup) -> UIAlertController? { guard group.contentGroupKind.isCustomizable || group.contentGroupKind.isGlobal else { return nil } let sheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let customizeExploreFeed = UIAlertAction(title: CommonStrings.customizeExploreFeedTitle, style: .default) { (_) in let exploreFeedSettingsViewController = ExploreFeedSettingsViewController() exploreFeedSettingsViewController.showCloseButton = true exploreFeedSettingsViewController.dataStore = self.dataStore exploreFeedSettingsViewController.apply(theme: self.theme) let themeableNavigationController = WMFThemeableNavigationController(rootViewController: exploreFeedSettingsViewController, theme: self.theme) self.present(themeableNavigationController, animated: true) } let hideThisCard = UIAlertAction(title: WMFLocalizedString("explore-feed-preferences-hide-card-action-title", value: "Hide this card", comment: "Title for action that allows users to hide a feed card"), style: .default) { (_) in FeedFunnel.shared.logFeedCardDismissed(for: FeedFunnelContext(group)) group.undoType = .contentGroup self.wantsDeleteInsertOnNextItemUpdate = true self.save() } guard let title = group.headerTitle else { assertionFailure("Expected header title for group \(group.contentGroupKind)") return nil } let hideAllCards = UIAlertAction(title: String.localizedStringWithFormat(WMFLocalizedString("explore-feed-preferences-hide-feed-cards-action-title", value: "Hide all “%@” cards", comment: "Title for action that allows users to hide all feed cards of given type - %@ is replaced with feed card type"), title), style: .default) { (_) in let feedContentController = self.dataStore.feedContentController // If there's only one group left it means that we're about to show an alert about turning off the Explore tab. In those cases, we don't want to provide the option to undo. if feedContentController.countOfVisibleContentGroupKinds > 1 { group.undoType = .contentGroupKind self.wantsDeleteInsertOnNextItemUpdate = true } feedContentController.toggleContentGroup(of: group.contentGroupKind, isOn: false, waitForCallbackFromCoordinator: true, apply: true, updateFeed: false) FeedFunnel.shared.logFeedCardDismissed(for: FeedFunnelContext(group)) } let cancel = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel) sheet.addAction(hideThisCard) sheet.addAction(hideAllCards) sheet.addAction(customizeExploreFeed) sheet.addAction(cancel) return sheet } func exploreCardCollectionViewCellWantsToUndoCustomization(_ cell: ExploreCardCollectionViewCell) { guard let vc = cell.cardContent as? ExploreCardViewController, let group = vc.contentGroup else { return } FeedFunnel.shared.logFeedCardRetained(for: FeedFunnelContext(group)) if group.undoType == .contentGroupKind { dataStore.feedContentController.toggleContentGroup(of: group.contentGroupKind, isOn: true, waitForCallbackFromCoordinator: false, apply: true, updateFeed: false) } group.undoType = .none wantsDeleteInsertOnNextItemUpdate = true if let indexPath = fetchedResultsController?.indexPath(forObject: group) { indexPathsForCollapsedCellsThatCanReappear.remove(indexPath) } save() } } // MARK: - WMFArticlePreviewingActionsDelegate extension ExploreViewController { override func shareArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, shareActivityController: UIActivityViewController) { super.shareArticlePreviewActionSelected(withArticleController: articleController, shareActivityController: shareActivityController) FeedFunnel.shared.logFeedShareTapped(for: previewed.context, index: previewed.indexPath?.item) } override func readMoreArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController) { articleController.wmf_removePeekableChildViewControllers() wmf_push(articleController, context: previewed.context, index: previewed.indexPath?.item, animated: true) } override func saveArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, didSave: Bool, articleURL: URL) { if didSave { ReadingListsFunnel.shared.logSaveInFeed(context: previewed.context, articleURL: articleURL, index: previewed.indexPath?.item) } else { ReadingListsFunnel.shared.logUnsaveInFeed(context: previewed.context, articleURL: articleURL, index: previewed.indexPath?.item) } } } // MARK: - EventLoggingSearchSourceProviding extension ExploreViewController: EventLoggingSearchSourceProviding { var searchSource: String { return "top_of_feed" } }
mit
adrfer/swift
test/attr/attr_iboutlet.swift
12
8900
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop @IBOutlet // expected-error {{only instance properties can be declared @IBOutlet}} {{1-11=}} var iboutlet_global: Int @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}} class IBOutletClassTy {} @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}} struct IBStructTy {} @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{1-11=}} func IBFunction() -> () {} @objc class IBOutletWrapperTy { @IBOutlet var value : IBOutletWrapperTy! = IBOutletWrapperTy() // no-warning @IBOutlet class var staticValue: IBOutletWrapperTy = 52 // expected-error {{cannot convert value of type 'Int' to specified type 'IBOutletWrapperTy'}} // expected-error@-2 {{only instance properties can be declared @IBOutlet}} {{3-12=}} // expected-error@-2 {{class stored properties not yet supported}} @IBOutlet // expected-error {{@IBOutlet may only be used on 'var' declarations}} {{3-13=}} func click() -> () {} @IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}} let immutable: IBOutletWrapperTy? = nil @IBOutlet // expected-error {{@IBOutlet attribute requires property to be mutable}} {{3-13=}} var computedImmutable: IBOutletWrapperTy? { return nil } } struct S { } enum E { } protocol P1 { } protocol P2 { } protocol CP1 : class { } protocol CP2 : class { } @objc protocol OP1 { } @objc protocol OP2 { } class NonObjC {} // Check where @IBOutlet can occur @objc class X { // Class type @IBOutlet var outlet2: X? @IBOutlet var outlet3: X! @IBOutlet var outlet1a: NonObjC // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}} @IBOutlet var outlet2a: NonObjC? // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}} @IBOutlet var outlet3a: NonObjC! // expected-error{{@IBOutlet property cannot have non-'@objc' class type 'NonObjC'}} {{3-13=}} // AnyObject @IBOutlet var outlet5: AnyObject? @IBOutlet var outlet6: AnyObject! // Protocol types @IBOutlet var outlet7: P1 // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type 'P1'}} {{3-13=}} @IBOutlet var outlet8: CP1 // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type 'CP1'}} {{3-13=}} @IBOutlet var outlet10: P1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet11: CP1? // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet12: OP1? @IBOutlet var outlet13: P1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet14: CP1! // expected-error{{@IBOutlet property cannot have non-'@objc' protocol type}} {{3-13=}} @IBOutlet var outlet15: OP1! // Class metatype @IBOutlet var outlet15b: X.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet16: X.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet17: X.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} // AnyClass @IBOutlet var outlet18: AnyClass // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet19: AnyClass? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet20: AnyClass! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} // Protocol types @IBOutlet var outlet21: P1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet22: CP1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet23: OP1.Type // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet24: P1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet25: CP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet26: OP1.Type? // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet27: P1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet28: CP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet29: OP1.Type! // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} // weak/unowned @IBOutlet weak var outlet30: X? @IBOutlet weak var outlet31: X! // String @IBOutlet var outlet33: String? @IBOutlet var outlet34: String! // Other bad cases @IBOutlet var outlet35: S // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet36: E // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet37: (X, X) // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var outlet38: Int // expected-error{{@IBOutlet property cannot have non-object type}} {{3-13=}} @IBOutlet var collection1b: [AnyObject]? @IBOutlet var collection1c: [AnyObject]! @IBOutlet var collection2b: [X]? @IBOutlet var collection2c: [X]! @IBOutlet var collection3b: [OP1]? @IBOutlet var collection3c: [OP1]! @IBOutlet var collection4a: [CP1] // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}} @IBOutlet var collection4b: ([CP1])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}} @IBOutlet var collection4c: ([CP1])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' protocol type}} {{3-13=}} @IBOutlet var collection5b: ([String])? // expected-error {{property cannot be marked @IBOutlet because its type cannot be represented in Objective-C}} @IBOutlet var collection5c: ([String])! // expected-error {{property cannot be marked @IBOutlet because its type cannot be represented in Objective-C}} @IBOutlet var collection6a: [NonObjC] // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}} @IBOutlet var collection6b: ([NonObjC])? // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}} @IBOutlet var collection6c: ([NonObjC])! // expected-error{{@IBOutlet property cannot be an array of non-'@objc' class type}} {{3-13=}} init() { } } @objc class Infer { @IBOutlet var outlet1: Infer! @IBOutlet weak var outlet2: Infer! func testOptionalNess() { _ = outlet1! _ = outlet2! } func testUnchecked() { _ = outlet1 _ = outlet2 } // This outlet is strong and optional. @IBOutlet var outlet4: AnyObject? func testStrong() { if outlet4 != nil {} } } @objc class C { } @objc protocol Proto { } class SwiftGizmo { @IBOutlet var a : C! @IBOutlet var b1 : [C] @IBOutlet var b2 : [C]! @IBOutlet var c : String! @IBOutlet var d : [String]! // expected-error{{property cannot be marked @IBOutlet because its type cannot be represented in Objective-C}} @IBOutlet var e : Proto! @IBOutlet var f : C? @IBOutlet var g : C! @IBOutlet weak var h : C? @IBOutlet weak var i : C! @IBOutlet unowned var j : C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '?' to form the optional type 'C?'}}{{30-30=?}} // expected-note @-2{{add '!' to form the implicitly unwrapped optional type 'C!'}}{{30-30=!}} @IBOutlet unowned(unsafe) var k : C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '?' to form the optional type 'C?'}}{{38-38=?}} // expected-note @-2{{add '!' to form the implicitly unwrapped optional type 'C!'}}{{38-38=!}} @IBOutlet var bad1 : Int // expected-error {{@IBOutlet property cannot have non-object type 'Int'}} {{3-13=}} @IBOutlet var dup: C! // expected-note{{'dup' previously declared here}} @IBOutlet var dup: C! // expected-error{{invalid redeclaration of 'dup'}} init() {} } class MissingOptional { @IBOutlet var a: C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '?' to form the optional type 'C?'}}{{21-21=?}} // expected-note @-2{{add '!' to form the implicitly unwrapped optional type 'C!'}}{{21-21=!}} @IBOutlet weak var b: C // expected-error{{@IBOutlet property has non-optional type 'C'}} // expected-note @-1{{add '!' to form the implicitly unwrapped optional type 'C!'}} {{26-26=!}} // expected-note @-2{{add '?' to form the optional type 'C?'}} {{26-26=?}} init() {} }
apache-2.0
vitormesquita/Malert
Example/Malert/AppDelegate.swift
1
2408
// // AppDelegate.swift // Malert // // Created by Vitor Mesquita on 10/31/2016. // Copyright (c) 2016 Vitor Mesquita. All rights reserved. // import UIKit import Malert @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { MalertView.appearance().buttonsHeight = 50 let window = UIWindow() window.rootViewController = BaseNavigationController(rootViewController: ListExamplesViewController()) self.window = window self.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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
royhsu/tiny-core
Sources/Core/Locale/Locale+CustomLocalizedStringConvertible.swift
1
365
// // Locale+CustomLocalizedStringConvertible.swift // AlleyCore // // Created by Roy Hsu on 2019/3/1. // Copyright © 2019 TinyWorld. All rights reserved. // // MARK: - CustomLocalizedStringConvertible extension Locale: CustomLocalizedStringConvertible { public var localizedDescription: String { return localizedString(forIdentifier: identifier)! } }
mit
adrfer/swift
test/SourceKit/CodeFormat/indent-with-tab.swift
11
1259
class Foo { var test : Int func foo() { test = 1 } } // RUN: %sourcekitd-test -req=format -line=1 -length=1 -req-opts=usetabs=1 %s >%t.response // RUN: %sourcekitd-test -req=format -line=2 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=3 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=4 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=5 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=6 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=7 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=8 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=9 -length=1 -req-opts=usetabs=1 %s >>%t.response // RUN: FileCheck --strict-whitespace %s <%t.response // CHECK: key.sourcetext: "class Foo {" // CHECK: key.sourcetext: " " // CHECK: key.sourcetext: " var test : Int" // CHECK: key.sourcetext: " " // CHECK: key.sourcetext: " func foo() {" // CHECK: key.sourcetext: " test = 1" // CHECK: key.sourcetext: " }" // CHECK: key.sourcetext: " " // CHECK: key.sourcetext: "}"
apache-2.0
carlo-/ipolito
iPoliTO2/SettingsViewController.swift
1
5024
// // SettingsViewController.swift // iPoliTO2 // // Created by Carlo Rapisarda on 30/07/2016. // Copyright © 2016 crapisarda. All rights reserved. // import UIKit import MessageUI class SettingsViewController: UITableViewController, MFMailComposeViewControllerDelegate { @IBOutlet var nameLabel: UILabel! @IBOutlet var usernameLabel: UILabel! private let logoutIndexPath = IndexPath(row: 1, section: 0) private let learnMoreIndexPath = IndexPath(row: 0, section: 1) private let feedbackIndexPath = IndexPath(row: 0, section: 2) private let reviewIndexPath = IndexPath(row: 0, section: 3) private let tellSomeFriendsIndexPath = IndexPath(row: 1, section: 3) override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { // Disable use of 'large title' display mode navigationItem.largeTitleDisplayMode = .never } let session = PTSession.shared nameLabel.text = session.studentInfo?.fullName ?? "???" usernameLabel.text = session.account?.studentID ?? "??" } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath { case logoutIndexPath: logoutPressed() case learnMoreIndexPath: learnMorePressed() case feedbackIndexPath: feedbackPressed() case reviewIndexPath: reviewPressed() case tellSomeFriendsIndexPath: tellSomeFriendsPressed() default: break } } func logoutPressed() { let alert = UIAlertController(title: ~"ls.settingsVC.logoutAlert.title", message: ~"ls.settingsVC.logoutAlert.body", preferredStyle: .alert) alert.addAction(UIAlertAction(title: ~"ls.generic.alert.cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: ~"ls.generic.alert.confirm", style: .destructive, handler: { action in self.performLogout() })) present(alert, animated: true, completion: nil) } func learnMorePressed() { let url = URL(string: PTConstants.gitHubReadmeLink)! UIApplication.shared.openURL(url) } func feedbackPressed() { if MFMailComposeViewController.canSendMail() { let subject = "iPoliTO -> Feedback" let body = "" presentEmailComposer(withSubject: subject, andBody: body) } else { showNoEmailAccountAlert() } } func reviewPressed() { let url = URL(string: PTConstants.appStoreReviewLink)! UIApplication.shared.openURL(url) } func tellSomeFriendsPressed() { let url = URL(string: PTConstants.appStoreLink) let text = ~"ls.settingsVC.tellSomeFriendsBody" presentSharePopup(withText: text, image: nil, andURL: url) } func presentEmailComposer(withSubject subject: String?, andBody body: String?) { guard MFMailComposeViewController.canSendMail() else { return } let composer = MFMailComposeViewController() composer.mailComposeDelegate = self composer.setSubject(subject ?? "") composer.setMessageBody(body ?? "", isHTML: false) composer.setToRecipients([PTConstants.feedbackEmail]) present(composer, animated: true, completion: nil) } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } func showNoEmailAccountAlert() { let title = ~"ls.generic.alert.error.title" let message = ~"ls.settingsVC.noEmailConfiguredAlert.body" let dismissal = ~"ls.generic.alert.dismiss" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: dismissal, style: .cancel, handler: nil)) } func presentSharePopup(withText text: String?, image: UIImage?, andURL url: URL?) { var items: [Any] = [] if (text != nil) { items.append(text!) } if (image != nil) { items.append(image!) } if (url != nil) { items.append(url!) } if items.isEmpty { return; } let activityVC = UIActivityViewController(activityItems: items, applicationActivities: nil) present(activityVC, animated: true, completion: nil) } func performLogout() { performSegue(withIdentifier: "unwindFromSettings_id", sender: self) if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.logout() } } }
gpl-3.0
CoderXiaoming/Ronaldo
SaleManager/SaleManager/AppDelegate.swift
1
2531
// // AppDelegate.swift // SaleManager // // Created by apple on 16/11/9. // Copyright © 2016年 YZH. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //MARK: - 程序启动完成后处理的事件 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /* 设置窗口根控制器,并显示 目前设置的是每次重新启动都要输入密码,所以启动时候的根控制器都是登录控制器。 */ window = UIWindow.init(frame: UIScreen.main.bounds) window?.rootViewController = SAMLoginController() window?.makeKeyAndVisible() //监听界面跳转通知 NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.loginSuccess(_:)), name: NSNotification.Name(rawValue: LoginSuccessNotification), object: nil) return true } //MARK: - 登录成功后的跳转操作 func loginSuccess(_ notification: Notification) { let anim = CATransition() anim.type = "fade" anim.duration = 0.7 window?.layer.add(anim, forKey: nil) window?.rootViewController = SAMMainTabBarController() } 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) { } func applicationWillEnterForeground(_ application: UIApplication) { } 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:. } }
apache-2.0
anjana-somathilake/Video-Ops
VideoPlayRecord/AppDelegate.swift
1
2154
// // AppDelegate.swift // VideoPlayRecord // // Created by Andy (Test) on 1/31/15. // Copyright (c) 2015 Ray Wenderlich. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ruslanskorb/CoreStore
Sources/CoreStoreObject+Convenience.swift
2
4684
// // CoreStoreObject+Convenience.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - CoreStoreObject extension CoreStoreObject { /** Exposes a `FetchableSource` that can fetch sibling objects of this `CoreStoreObject` instance. This may be the `DataStack`, a `BaseDataTransaction`, the `NSManagedObjectContext` itself, or `nil` if the obejct's parent is already deallocated. - Warning: Future implementations may change the instance returned by this method depending on the timing or condition that `fetchSource()` was called. Do not make assumptions that the instance will be a specific instance. If the `NSManagedObjectContext` instance is desired, use the `FetchableSource.unsafeContext()` method to get the correct instance. Also, do not assume that the `fetchSource()` and `querySource()` return the same instance all the time. - returns: a `FetchableSource` that can fetch sibling objects of this `CoreStoreObject` instance. This may be the `DataStack`, a `BaseDataTransaction`, the `NSManagedObjectContext` itself, or `nil` if the object's parent is already deallocated. */ @nonobjc public func fetchSource() -> FetchableSource? { guard let context = self.rawObject!.managedObjectContext else { return nil } if context.isTransactionContext { return context.parentTransaction } if context.isDataStackContext { return context.parentStack } return context } /** Exposes a `QueryableSource` that can query attributes and aggregate values. This may be the `DataStack`, a `BaseDataTransaction`, the `NSManagedObjectContext` itself, or `nil` if the obejct's parent is already deallocated. - Warning: Future implementations may change the instance returned by this method depending on the timing or condition that `querySource()` was called. Do not make assumptions that the instance will be a specific instance. If the `NSManagedObjectContext` instance is desired, use the `QueryableSource.unsafeContext()` method to get the correct instance. Also, do not assume that the `fetchSource()` and `querySource()` return the same instance all the time. - returns: a `QueryableSource` that can query attributes and aggregate values. This may be the `DataStack`, a `BaseDataTransaction`, the `NSManagedObjectContext` itself, or `nil` if the object's parent is already deallocated. */ @nonobjc public func querySource() -> QueryableSource? { guard let context = self.rawObject!.managedObjectContext else { return nil } if context.isTransactionContext { return context.parentTransaction } if context.isDataStackContext { return context.parentStack } return context } /** Re-faults the object to use the latest values from the persistent store */ @nonobjc public func refreshAsFault() { let rawObject = self.rawObject! rawObject.managedObjectContext?.refresh(rawObject, mergeChanges: false) } /** Re-faults the object to use the latest values from the persistent store and merges previously pending changes back */ @nonobjc public func refreshAndMerge() { let rawObject = self.rawObject! rawObject.managedObjectContext?.refresh(rawObject, mergeChanges: true) } }
mit
Octadero/TensorFlow
Sources/Proto/contrib/makefile/downloads/protobuf/src/google/protobuf/unittest_no_generic_services.pb.swift
1
7680
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: tensorflow/contrib/makefile/downloads/protobuf/src/google/protobuf/unittest_no_generic_services.proto // // For information on using the generated types, please see the documenation: // https://github.com/apple/swift-protobuf/ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that your are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } public enum Google_Protobuf_NoGenericServicesTest_TestEnum: SwiftProtobuf.Enum { public typealias RawValue = Int case foo // = 1 public init() { self = .foo } public init?(rawValue: Int) { switch rawValue { case 1: self = .foo default: return nil } } public var rawValue: Int { switch self { case .foo: return 1 } } } public struct Google_Protobuf_NoGenericServicesTest_TestMessage: SwiftProtobuf.ExtensibleMessage { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var a: Int32 { get {return _a ?? 0} set {_a = newValue} } /// Returns true if `a` has been explicitly set. public var hasA: Bool {return self._a != nil} /// Clears the value of `a`. Subsequent reads from it will return its default value. public mutating func clearA() {self._a = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} public var _protobuf_extensionFieldValues = SwiftProtobuf.ExtensionFieldValueSet() fileprivate var _a: Int32? = nil } // MARK: - Extension support defined in unittest_no_generic_services.proto. extension Google_Protobuf_NoGenericServicesTest_TestMessage { public var Google_Protobuf_NoGenericServicesTest_testExtension: Int32 { get {return getExtensionValue(ext: Google_Protobuf_NoGenericServicesTest_Extensions_test_extension) ?? 0} set {setExtensionValue(ext: Google_Protobuf_NoGenericServicesTest_Extensions_test_extension, value: newValue)} } /// Returns true if extension `Google_Protobuf_NoGenericServicesTest_Extensions_test_extension` /// has been explicitly set. public var hasGoogle_Protobuf_NoGenericServicesTest_testExtension: Bool { return hasExtensionValue(ext: Google_Protobuf_NoGenericServicesTest_Extensions_test_extension) } /// Clears the value of extension `Google_Protobuf_NoGenericServicesTest_Extensions_test_extension`. /// Subsequent reads from it will return its default value. public mutating func clearGoogle_Protobuf_NoGenericServicesTest_testExtension() { clearExtensionValue(ext: Google_Protobuf_NoGenericServicesTest_Extensions_test_extension) } } /// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by /// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed /// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create /// a larger `SwiftProtobuf.SimpleExtensionMap`. public let Google_Protobuf_NoGenericServicesTest_UnittestNoGenericServices_Extensions: SwiftProtobuf.SimpleExtensionMap = [ Google_Protobuf_NoGenericServicesTest_Extensions_test_extension ] let Google_Protobuf_NoGenericServicesTest_Extensions_test_extension = SwiftProtobuf.MessageExtension<SwiftProtobuf.OptionalExtensionField<SwiftProtobuf.ProtobufInt32>, Google_Protobuf_NoGenericServicesTest_TestMessage>( _protobuf_fieldNumber: 1000, fieldName: "google.protobuf.no_generic_services_test.test_extension" ) // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "google.protobuf.no_generic_services_test" extension Google_Protobuf_NoGenericServicesTest_TestEnum: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "FOO"), ] } extension Google_Protobuf_NoGenericServicesTest_TestMessage: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".TestMessage" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "a"), ] public var isInitialized: Bool { if !_protobuf_extensionFieldValues.isInitialized {return false} return true } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularInt32Field(value: &self._a) case 1000..<536870912: try decoder.decodeExtensionField(values: &_protobuf_extensionFieldValues, messageType: Google_Protobuf_NoGenericServicesTest_TestMessage.self, fieldNumber: fieldNumber) default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._a { try visitor.visitSingularInt32Field(value: v, fieldNumber: 1) } try visitor.visitExtensionFields(fields: _protobuf_extensionFieldValues, start: 1000, end: 536870912) try unknownFields.traverse(visitor: &visitor) } public func _protobuf_generated_isEqualTo(other: Google_Protobuf_NoGenericServicesTest_TestMessage) -> Bool { if self._a != other._a {return false} if unknownFields != other.unknownFields {return false} if _protobuf_extensionFieldValues != other._protobuf_extensionFieldValues {return false} return true } }
gpl-3.0
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+SampleTests.swift
13
5851
// // Observable+SampleTests.swift // Tests // // Created by Krunoslav Zaher on 4/29/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import XCTest import RxSwift import RxTest class ObservableSampleTest : RxTest { } extension ObservableSampleTest { func testSample_Sampler_SamplerThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(220, 2), next(240, 3), next(290, 4), next(300, 5), next(310, 6), completed(400) ]) let ys = scheduler.createHotObservable([ next(150, ""), next(210, "bar"), next(250, "foo"), next(260, "qux"), error(320, testError) ]) let res = scheduler.start { xs.sample(ys) } let correct = [ next(250, 3), error(320, testError) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 320) ]) XCTAssertEqual(ys.subscriptions, [ Subscription(200, 320) ]) } func testSample_Sampler_Simple1() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(220, 2), next(240, 3), next(290, 4), next(300, 5), next(310, 6), completed(400) ]) let ys = scheduler.createHotObservable([ next(150, ""), next(210, "bar"), next(250, "foo"), next(260, "qux"), next(320, "baz"), completed(500) ]) let res = scheduler.start { xs.sample(ys) } let correct = [ next(250, 3), next(320, 6), completed(500) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) XCTAssertEqual(ys.subscriptions, [ Subscription(200, 500) ]) } func testSample_Sampler_Simple2() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(220, 2), next(240, 3), next(290, 4), next(300, 5), next(310, 6), next(360, 7), completed(400) ]) let ys = scheduler.createHotObservable([ next(150, ""), next(210, "bar"), next(250, "foo"), next(260, "qux"), next(320, "baz"), completed(500) ]) let res = scheduler.start { xs.sample(ys) } let correct = [ next(250, 3), next(320, 6), next(500, 7), completed(500) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) XCTAssertEqual(ys.subscriptions, [ Subscription(200, 500) ]) } func testSample_Sampler_Simple3() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(220, 2), next(240, 3), next(290, 4), completed(300) ]) let ys = scheduler.createHotObservable([ next(150, ""), next(210, "bar"), next(250, "foo"), next(260, "qux"), next(320, "baz"), completed(500) ]) let res = scheduler.start { xs.sample(ys) } let correct = [ next(250, 3), next(320, 4), completed(320) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 300) ]) XCTAssertEqual(ys.subscriptions, [ Subscription(200, 320) ]) } func testSample_Sampler_SourceThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(220, 2), next(240, 3), next(290, 4), next(300, 5), next(310, 6), error(320, testError) ]) let ys = scheduler.createHotObservable([ next(150, ""), next(210, "bar"), next(250, "foo"), next(260, "qux"), next(300, "baz"), completed(400) ]) let res = scheduler.start { xs.sample(ys) } let correct = [ next(250, 3), next(300, 5), error(320, testError) ] XCTAssertEqual(res.events, correct) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 320) ]) XCTAssertEqual(ys.subscriptions, [ Subscription(200, 320) ]) } #if TRACE_RESOURCES func testSampleReleasesResourcesOnComplete() { let scheduler = TestScheduler(initialClock: 0) _ = Observable<Int>.just(1).throttle(0.0, latest: true, scheduler: scheduler).subscribe() scheduler.start() } func testSamepleReleasesResourcesOnError() { let scheduler = TestScheduler(initialClock: 0) _ = Observable<Int>.error(testError).throttle(0.0, latest: true, scheduler: scheduler).subscribe() scheduler.start() } #endif }
mit
zerovagner/iOS-Studies
RainyShinyCloudy/RainyShinyCloudy/AppDelegate.swift
1
2095
// // AppDelegate.swift // RainyShinyCloudy // // Created by Vagner Oliveira on 5/12/17. // Copyright © 2017 Vagner Oliveira. 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:. } }
gpl-3.0
dcelasun/thrift
lib/swift/Tests/ThriftTests/TSocketServerTests.swift
11
1773
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import XCTest import Foundation @testable import Thrift private protocol CalculatorService { } private class Calculator: CalculatorService { } private class CalculatorProcessor: TProcessor { private let service: CalculatorService init(service: CalculatorService) { self.service = service } var processCalled = false func process(on inProtocol: TProtocol, outProtocol: TProtocol) throws { processCalled = true } } class TSocketServerTests: XCTestCase { func testInit() throws { let service: CalculatorService = Calculator() let processor: CalculatorProcessor = CalculatorProcessor(service: service) let _: TSocketServer<TBinaryProtocol, TBinaryProtocol, CalculatorProcessor> = try TSocketServer(port: 9090, inProtocol: TBinaryProtocol.self, outProtocol: TBinaryProtocol.self, processor: processor) } static var allTests : [(String, (TSocketServerTests) -> () throws -> Void)] { return [ ("testInit", testInit), ] } }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/06236-swift-typebase-getdesugaredtype.swift
11
218
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{protocol A:A{ func g typealias b struct g:b
mit
jlandon/Alexandria
Tests/AlexandriaTests/URLTests.swift
2
1949
// // URLTests.swift // // Created by Jonathan Landon on 10/26/16. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Oven Bits, LLC // // 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 XCTest import Alexandria class URLTests: XCTestCase { func testStringLiteralInitializer() { let url: URL = "https://github.com/ovenbits" XCTAssert(url.absoluteString == "https://github.com/ovenbits", "Absolute strings are not equal") XCTAssert(url.scheme == "https", "Scheme are not equal") XCTAssert(url.host == "github.com", "Hosts are not equal") XCTAssert(url.path == "/ovenbits", "Paths are not equal") } func testPathAppendingOperator() { var url: URL = "https://github.com" url = url + "ovenbits" url = url + "Alexandria" XCTAssert(url.path == "/ovenbits/Alexandria", "Paths are not equal") } }
mit
mukyasa/MMTextureChat
Pods/MBPhotoPicker/Pod/Classes/MBPhotoPicker.swift
1
11909
// // MBPhotoPicker.swift // MBPhotoPicker // // Created by Marcin Butanowicz on 02/01/16. // Copyright © 2016 MBSSoftware. All rights reserved. // import UIKit import Photos import MobileCoreServices open class MBPhotoPicker: NSObject { // MARK: Localized strings open var alertTitle: String? = "Alert title" open var alertMessage: String? = "Alert message" open var actionTitleCancel: String = "Action Cancel" open var actionTitleTakePhoto: String = "Action take photo" open var actionTitleLastPhoto: String = "Action last photo" open var actionTitleOther: String = "Action other" open var actionTitleLibrary: String = "Action Library" // MARK: Photo picker settings open var allowDestructive: Bool = false open var allowEditing: Bool = false open var disableEntitlements: Bool = false open var cameraDevice: UIImagePickerControllerCameraDevice = .rear open var cameraFlashMode: UIImagePickerControllerCameraFlashMode = .auto open var resizeImage: CGSize? /** Using for iPad devices */ open var presentPhotoLibraryInPopover = false open var popoverTarget: UIView? open var popoverRect: CGRect? open var popoverDirection: UIPopoverArrowDirection = .any var popoverController: UIPopoverController? /** List of callbacks variables */ open var onPhoto: ((_ image: UIImage?) -> ())? open var onPresented: (() -> ())? open var onCancel: (() -> ())? open var onError: ((_ error: ErrorPhotoPicker) -> ())? // MARK: Error's definition @objc public enum ErrorPhotoPicker: Int { case cameraNotAvailable case libraryNotAvailable case accessDeniedToCameraRoll case accessDeniedToPhoto case entitlementiCloud case wrongFileType case popoverTarget case other public func name() -> String { switch self { case .cameraNotAvailable: return "Camera not available" case .libraryNotAvailable: return "Library not available" case .accessDeniedToCameraRoll: return "Access denied to camera roll" case .accessDeniedToPhoto: return "Access denied to photo library" case .entitlementiCloud: return "Missing iCloud Capatability" case .wrongFileType: return "Wrong file type" case .popoverTarget: return "Missing property popoverTarget while iPad is run" case .other: return "Other" } } } // MARK: Public open func present() { let topController = UIApplication.shared.windows.first?.rootViewController present(topController!) } open func present(_ controller: UIViewController!) { self.controller = controller let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .actionSheet) let actionTakePhoto = UIAlertAction(title: self.localizeString(actionTitleTakePhoto), style: .default, handler: { (alert: UIAlertAction!) in if UIImagePickerController.isSourceTypeAvailable(.camera) { self.presentImagePicker(.camera, topController: controller) } else { self.onError?(.cameraNotAvailable) } }) let actionLibrary = UIAlertAction(title: self.localizeString(actionTitleLibrary), style: .default, handler: { (alert: UIAlertAction!) in if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { self.presentImagePicker(.photoLibrary, topController: controller) } else { self.onError?(.libraryNotAvailable) } }) let actionLast = UIAlertAction(title: self.localizeString(actionTitleLastPhoto), style: .default, handler: { (alert: UIAlertAction!) in self.lastPhotoTaken({ (image) in self.photoHandler(image) }, errorHandler: { (error) in self.onError?(error) } ) }) let actionCancel = UIAlertAction(title: self.localizeString(actionTitleCancel), style: allowDestructive ? .destructive : .cancel, handler: { (alert: UIAlertAction!) in self.onCancel?() }) alert.addAction(actionTakePhoto) alert.addAction(actionLibrary) alert.addAction(actionLast) alert.addAction(actionCancel) if !self.disableEntitlements { let actionOther = UIAlertAction(title: self.localizeString(actionTitleOther), style: .default, handler: { (alert: UIAlertAction!) in let document = UIDocumentMenuViewController(documentTypes: [kUTTypeImage as String, kUTTypeJPEG as String, kUTTypePNG as String, kUTTypeBMP as String, kUTTypeTIFF as String], in: .import) document.delegate = self controller.present(document, animated: true, completion: nil) }) alert.addAction(actionOther) } if UIDevice.current.userInterfaceIdiom == .pad { guard let popover = self.popoverTarget else { self.onError?(.popoverTarget) return; } if let presenter = alert.popoverPresentationController { alert.modalPresentationStyle = .popover presenter.sourceView = popover; presenter.permittedArrowDirections = self.popoverDirection if let rect = self.popoverRect { presenter.sourceRect = rect } else { presenter.sourceRect = popover.bounds } } } controller.present(alert, animated: true) { () in self.onPresented?() } } // MARK: Private internal weak var controller: UIViewController? var imagePicker: UIImagePickerController! func presentImagePicker(_ sourceType: UIImagePickerControllerSourceType, topController: UIViewController!) { imagePicker = UIImagePickerController() imagePicker.sourceType = sourceType imagePicker.delegate = self imagePicker.isEditing = self.allowEditing if sourceType == .camera { imagePicker.cameraDevice = self.cameraDevice if UIImagePickerController.isFlashAvailable(for: self.cameraDevice) { imagePicker.cameraFlashMode = self.cameraFlashMode } } if UIDevice.current.userInterfaceIdiom == .pad && sourceType == .photoLibrary && self.presentPhotoLibraryInPopover { guard let popover = self.popoverTarget else { self.onError?(.popoverTarget) return; } self.popoverController = UIPopoverController(contentViewController: imagePicker) let rect = self.popoverRect ?? CGRect.zero self.popoverController?.present(from: rect, in: popover, permittedArrowDirections: self.popoverDirection, animated: true) } else { topController.present(imagePicker, animated: true, completion: nil) } } func photoHandler(_ image: UIImage!) { let resizedImage: UIImage = UIImage.resizeImage(image, newSize: self.resizeImage) self.onPhoto?(resizedImage) } func localizeString(_ string: String!) -> String! { var string = string let podBundle = Bundle(for: self.classForCoder) if let bundleURL = podBundle.url(forResource: "MBPhotoPicker", withExtension: "bundle") { if let bundle = Bundle(url: bundleURL) { string = NSLocalizedString(string!, tableName: "Localizable", bundle: bundle, value: "", comment: "") } else { assertionFailure("Could not load the bundle") } } return string! } } extension MBPhotoPicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate { public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true) { () in self.onCancel?() } } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] { self.photoHandler(image as! UIImage) } else { self.onError?(.other) } picker.dismiss(animated: true, completion: nil) self.popoverController = nil } public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { picker.dismiss(animated: true, completion: nil) self.popoverController = nil } } extension MBPhotoPicker: UIDocumentPickerDelegate { public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { var error: NSError? let filerCordinator = NSFileCoordinator() filerCordinator.coordinate(readingItemAt: url, options: .withoutChanges, error: &error, byAccessor: { (url: URL) in if let data: Data = try? Data(contentsOf: url) { if data.isSupportedImageType() { if let image: UIImage = UIImage(data: data) { self.photoHandler(image) } else { self.onError?(.other) } } else { self.onError?(.wrongFileType) } } else { self.onError?(.other) } }) } public func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { self.onCancel?() } } extension MBPhotoPicker: UIDocumentMenuDelegate { public func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { documentPicker.delegate = self self.controller?.present(documentPicker, animated: true, completion: nil) } public func documentMenuWasCancelled(_ documentMenu: UIDocumentMenuViewController) { self.onCancel?() } } extension MBPhotoPicker { internal func lastPhotoTaken (_ completionHandler: @escaping (_ image: UIImage?) -> (), errorHandler: @escaping (_ error: ErrorPhotoPicker) -> ()) { PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) -> () in if (status == PHAuthorizationStatus.authorized) { let manager = PHImageManager.default() let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: true)] let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions) let asset: PHAsset? = fetchResult.lastObject let initialRequestOptions = PHImageRequestOptions() initialRequestOptions.isSynchronous = true initialRequestOptions.resizeMode = .fast initialRequestOptions.deliveryMode = .fastFormat manager.requestImageData(for: asset!, options: initialRequestOptions) { (data: Data?, title: String?, orientation: UIImageOrientation, info: [AnyHashable: Any]?) -> () in guard let dataImage = data else { errorHandler(.other) return } let image:UIImage = UIImage(data: dataImage)! DispatchQueue.main.async(execute: { () in completionHandler(image) }) } } else { errorHandler(.accessDeniedToPhoto) } } } } extension UIImage { static public func resizeImage(_ image: UIImage!, newSize: CGSize?) -> UIImage! { guard var size = newSize else { return image } let widthRatio = size.width/image.size.width let heightRatio = size.height/image.size.height let ratio = min(widthRatio, heightRatio) size = CGSize(width: image.size.width*ratio, height: image.size.height*ratio) UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) image.draw(in: CGRect(origin: CGPoint.zero, size: size)) let scaledImage: UIImage! = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } } extension Data { public func isSupportedImageType() -> Bool { var c = [UInt32](repeating: 0, count: 1) (self as NSData).getBytes(&c, length: 1) switch (c[0]) { case 0xFF, 0x89, 0x00, 0x4D, 0x49, 0x47, 0x42: return true default: return false } } }
mit
eviathan/Salt
Pepper/Code Examples/Apple/AudioUnitV3ExampleABasicAudioUnitExtensionandHostImplementation/Filter/iOS/FilterDemoFramework/FilterView.swift
1
23054
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: View for the FilterDemo audio unit. This lets the user adjust the filter cutoff frequency and resonance on an X-Y grid. */ import UIKit /* The `FilterViewDelegate` protocol is used to notify a delegate (`FilterDemoViewController`) when the user has changed the frequency or resonance by tapping and dragging in the graph. `filterViewDataDidChange(_:)` is called when the view size changes and new frequency data is available. */ protocol FilterViewDelegate: class { func filterView(_ filterView: FilterView, didChangeResonance resonance: Float) func filterView(_ filterView: FilterView, didChangeFrequency frequency: Float) func filterView(_ filterView: FilterView, didChangeFrequency frequency: Float, andResonance resonance: Float) func filterViewDataDidChange(_ filterView: FilterView) } class FilterView: UIView { // MARK: Properties static let defaultMinHertz: Float = 12.0 static let defaultMaxHertz: Float = 22050.0 let logBase = 2 let leftMargin: CGFloat = 54.0 let rightMargin: CGFloat = 10.0 let bottomMargin: CGFloat = 40.0 let numDBLines = 4 let defaultGain = 20 let gridLineCount = 11 let labelWidth: CGFloat = 40.0 let maxNumberOfResponseFrequencies = 1024 var frequencies: [Double]? var dbLabels = [CATextLayer]() var frequencyLabels = [CATextLayer]() var dbLines = [CALayer]() var freqLines = [CALayer]() var controls = [CALayer]() var containerLayer = CALayer() var graphLayer = CALayer() var curveLayer: CAShapeLayer? // The delegate to notify of paramater and size changes. weak var delegate: FilterViewDelegate? var editPoint = CGPoint.zero var touchDown = false var resonance: Float = 0.0 { willSet { } didSet { // Clamp the resonance to min/max values. if resonance > Float(defaultGain) { resonance = Float(defaultGain) } else if resonance < Float(-defaultGain) { resonance = Float(-defaultGain) } editPoint.y = floor(locationForDBValue(resonance)) // Do not notify delegate that the resonance changed; that would create a feedback loop. } } var frequency: Float = FilterView.defaultMinHertz { willSet { } didSet { if frequency > FilterView.defaultMaxHertz { frequency = FilterView.defaultMaxHertz } else if frequency < FilterView.defaultMinHertz { frequency = FilterView.defaultMinHertz } editPoint.x = floor(locationForFrequencyValue(frequency)) // Do not notify delegate that the frequency changed; that would create a feedback loop. } } /* The frequencies are plotted on a logorithmic scale. This method returns a frequency value based on a fractional grid position. */ func valueAtGridIndex(_ index: Float) -> Float { return FilterView.defaultMinHertz * powf(Float(logBase), index) } func logValueForNumber(_ number: Float, base: Float) -> Float { return logf(number) / logf(base) } /* Prepares an array of frequencies that the AU needs to supply magnitudes for. This array is cached until the view size changes (on device rotation, etc). */ func frequencyDataForDrawing() -> [Double] { guard frequencies == nil else { return frequencies! } let width = graphLayer.bounds.width let rightEdge = width + leftMargin var pixelRatio = Int(ceil(width / CGFloat(maxNumberOfResponseFrequencies))) var location = leftMargin var locationsCount = maxNumberOfResponseFrequencies if pixelRatio <= 1 { pixelRatio = 1 locationsCount = Int(width) } frequencies = (0..<locationsCount).map { _ in if location > rightEdge { return Double(FilterView.defaultMaxHertz) } else { var frequency = frequencyValueForLocation(location) if frequency > FilterView.defaultMaxHertz { frequency = FilterView.defaultMaxHertz } location += CGFloat(pixelRatio) return Double(frequency) } } return frequencies! } /* Generates a bezier path from the frequency response curve data provided by the view controller. Also responsible for keeping the control point in sync. */ func setMagnitudes(_ magnitudeData: [Double]) { // If no curve layer exists, create one using the configuration closure. curveLayer = curveLayer ?? { let curveLayer = CAShapeLayer() curveLayer.fillColor = UIColor(red: 0.31, green: 0.37, blue: 0.73, alpha: 0.8).cgColor graphLayer.addSublayer(curveLayer) return curveLayer }() let bezierPath = CGMutablePath() let width = graphLayer.bounds.width bezierPath.move(to: CGPoint(x: leftMargin, y: graphLayer.frame.height + bottomMargin)) var lastDBPos: CGFloat = 0.0 var location: CGFloat = leftMargin let frequencyCount = frequencies?.count ?? 0 let pixelRatio = Int(ceil(width / CGFloat(frequencyCount))) for i in 0 ..< frequencyCount { let dbValue = 20.0 * log10(magnitudeData[i]) var dbPos: CGFloat = 0.0 switch dbValue { case let x where x < Double(-defaultGain): dbPos = locationForDBValue(Float(-defaultGain)) case let x where x > Double(defaultGain): dbPos = locationForDBValue(Float(defaultGain)) default: dbPos = locationForDBValue(Float(dbValue)) } if fabs(lastDBPos - dbPos) >= 0.1 { bezierPath.addLine(to: CGPoint(x: location, y: dbPos)) } lastDBPos = dbPos location += CGFloat(pixelRatio) if location > width + graphLayer.frame.origin.x { location = width + graphLayer.frame.origin.x break } } bezierPath.addLine(to: CGPoint(x: location, y: graphLayer.frame.origin.y + graphLayer.frame.height + bottomMargin)) bezierPath.closeSubpath() // Turn off implict animation on the curve layer. CATransaction.begin() CATransaction.setDisableActions(true) curveLayer!.path = bezierPath CATransaction.commit() updateControls(true) } /* Calculates the pixel position on the y axis of the graph corresponding to the dB value. */ func locationForDBValue(_ value: Float) -> CGFloat { let step = graphLayer.frame.height / CGFloat(defaultGain * 2) let location = (CGFloat(value) + CGFloat(defaultGain)) * step return graphLayer.frame.height - location + bottomMargin } /* Calculates the pixel position on the x axis of the graph corresponding to the frequency value. */ func locationForFrequencyValue(_ value: Float) -> CGFloat { let pixelIncrement = graphLayer.frame.width / CGFloat(gridLineCount) let number = value / Float(FilterView.defaultMinHertz) let location = logValueForNumber(number, base: Float(logBase)) * Float(pixelIncrement) return floor(CGFloat(location) + graphLayer.frame.origin.x) + 0.5 } /* Calculates the dB value corresponding to a position value on the y axis of the graph. */ func dbValueForLocation(_ location: CGFloat) -> Float { let step = graphLayer.frame.height / CGFloat(defaultGain * 2) return Float(-(((location - bottomMargin) / step) - CGFloat(defaultGain))) } /* Calculates the frequency value corresponding to a position value on the x axis of the graph. */ func frequencyValueForLocation(_ location: CGFloat) -> Float { let pixelIncrement = graphLayer.frame.width / CGFloat(gridLineCount) let index = (location - graphLayer.frame.origin.x) / CGFloat(pixelIncrement) return valueAtGridIndex(Float(index)) } /* Provides a properly formatted string with an appropriate precision for the input value. */ func stringForValue(_ value: Float) -> String { var temp = value if value >= 1000 { temp = temp / 1000 } temp = floor((temp * 100.0) / 100.0) if floor(temp) == temp { return String(format: "%.0f", temp) } else { return String(format: "%.1f", temp) } } override func awakeFromNib() { // Create all of the CALayers for the graph, lines, and labels. let scale = UIScreen.main.scale containerLayer.name = "container" containerLayer.anchorPoint = CGPoint.zero containerLayer.frame = CGRect(origin: CGPoint.zero, size: layer.bounds.size) containerLayer.bounds = containerLayer.frame containerLayer.contentsScale = scale layer.addSublayer(containerLayer) graphLayer.name = "graph background" graphLayer.borderColor = UIColor.darkGray.cgColor graphLayer.borderWidth = 1.0 graphLayer.backgroundColor = UIColor(white: 0.88, alpha: 1.0).cgColor graphLayer.bounds = CGRect(x: 0, y: 0, width: layer.frame.width - leftMargin, height: layer.frame.height - bottomMargin) graphLayer.position = CGPoint(x: leftMargin, y: 0) graphLayer.anchorPoint = CGPoint.zero graphLayer.contentsScale = scale containerLayer.addSublayer(graphLayer) layer.contentsScale = scale createDBLabelsAndLines() createFrequencyLabelsAndLines() createControlPoint() } /* Creates the decibel label layers for the vertical axis of the graph and adds them as sublayers of the graph layer. Also creates the db Lines. */ func createDBLabelsAndLines() { var value: Int let scale = layer.contentsScale for index in -numDBLines ... numDBLines { value = index * (defaultGain / numDBLines) if index >= -numDBLines && index <= numDBLines { let labelLayer = CATextLayer() // Create the label layers and set their properties. labelLayer.string = "\(value) db" labelLayer.name = String(index) labelLayer.font = UIFont.systemFont(ofSize: 14).fontName as CFTypeRef labelLayer.fontSize = 14 labelLayer.contentsScale = scale labelLayer.foregroundColor = UIColor(white: 0.1, alpha: 1.0).cgColor labelLayer.alignmentMode = kCAAlignmentRight dbLabels.append(labelLayer) containerLayer.addSublayer(labelLayer) // Create the line labels. let lineLayer = CALayer() if index == 0 { lineLayer.backgroundColor = UIColor(white: 0.65, alpha: 1.0).cgColor } else { lineLayer.backgroundColor = UIColor(white: 0.8, alpha: 1.0).cgColor } dbLines.append(lineLayer) graphLayer.addSublayer(lineLayer) } } } /* Creates the frequency label layers for the horizontal axis of the graph and adds them as sublayers of the graph layer. Also creates the frequency line layers. */ func createFrequencyLabelsAndLines() { var value: Float var firstK = true let scale = layer.contentsScale for index in 0 ... gridLineCount { value = valueAtGridIndex(Float(index)) // Create the label layers and set their properties. let labelLayer = CATextLayer() labelLayer.font = UIFont.systemFont(ofSize: 14).fontName as CFTypeRef labelLayer.foregroundColor = UIColor(white: 0.1, alpha: 1.0).cgColor labelLayer.fontSize = 14 labelLayer.alignmentMode = kCAAlignmentCenter labelLayer.contentsScale = scale labelLayer.anchorPoint = CGPoint.zero frequencyLabels.append(labelLayer) // Create the line layers. if index > 0 && index < gridLineCount { let lineLayer: CALayer = CALayer() lineLayer.backgroundColor = UIColor(white: 0.8, alpha: 1.0).cgColor freqLines.append(lineLayer) graphLayer.addSublayer(lineLayer) var s = stringForValue(value) if value >= 1000 && firstK { s += "K" firstK = false } labelLayer.string = s } else if index == 0 { labelLayer.string = "\(stringForValue(value)) Hz" } else { labelLayer.string = "\(stringForValue(FilterView.defaultMaxHertz)) K" } containerLayer.addSublayer(labelLayer) } } /* Creates the control point layers comprising of a horizontal and vertical line (crosshairs) and a circle at the intersection. */ func createControlPoint() { var lineLayer = CALayer() let controlColor = touchDown ? tintColor.cgColor: UIColor.darkGray.cgColor lineLayer.backgroundColor = controlColor lineLayer.name = "x" controls.append(lineLayer) graphLayer.addSublayer(lineLayer) lineLayer = CALayer() lineLayer.backgroundColor = controlColor lineLayer.name = "y" controls.append(lineLayer) graphLayer.addSublayer(lineLayer) let circleLayer = CALayer() circleLayer.borderColor = controlColor circleLayer.borderWidth = 2.0 circleLayer.cornerRadius = 3.0 circleLayer.name = "point" controls.append(circleLayer) graphLayer.addSublayer(circleLayer) } /* Updates the position of the control layers and the color if the refreshColor parameter is true. The controls are drawn in a blue color if the user's finger is touching the graph and still down. */ func updateControls (_ refreshColor: Bool) { let color = touchDown ? tintColor.cgColor: UIColor.darkGray.cgColor // Turn off implicit animations for the control layers to avoid any control lag. CATransaction.begin() CATransaction.setDisableActions(true) for layer in controls { switch layer.name! { case "point": layer.frame = CGRect(x: editPoint.x - 3, y: editPoint.y-3, width: 7, height: 7).integral layer.position = editPoint if refreshColor { layer.borderColor = color } case "x": layer.frame = CGRect(x: graphLayer.frame.origin.x, y: floor(editPoint.y + 0.5), width: graphLayer.frame.width, height: 1.0) if refreshColor { layer.backgroundColor = color } case "y": layer.frame = CGRect(x: floor(editPoint.x) + 0.5, y: bottomMargin, width: 1.0, height: graphLayer.frame.height) if refreshColor { layer.backgroundColor = color } default: layer.frame = CGRect.zero } } CATransaction.commit() } func updateDBLayers() { // Update the positions of the dBLine and label layers. for index in -numDBLines ... numDBLines { let location = floor(locationForDBValue(Float(index * (defaultGain / numDBLines)))) if index >= -numDBLines && index <= numDBLines { dbLines[index + 4].frame = CGRect(x: graphLayer.frame.origin.x, y: location, width: graphLayer.frame.width, height: 1.0) dbLabels[index + 4].frame = CGRect(x: 0.0, y: location - bottomMargin - 8, width: leftMargin - 7.0, height: 16.0) } } } func updateFrequencyLayers() { // Update the positions of the frequency line and label layers. for index in 0 ... gridLineCount { let value = valueAtGridIndex(Float(index)) let location = floor(locationForFrequencyValue(value)) if index > 0 && index < gridLineCount { freqLines[index - 1].frame = CGRect(x: location, y: bottomMargin, width: 1.0, height: graphLayer.frame.height) frequencyLabels[index].frame = CGRect(x: location - labelWidth / 2.0, y: graphLayer.frame.height, width: labelWidth, height: 16.0) } frequencyLabels[index].frame = CGRect(x: location - labelWidth / 2.0, y: graphLayer.frame.height + 6, width: labelWidth + rightMargin, height: 16.0) } } /* This function positions all of the layers of the view starting with the horizontal dbLines and lables on the y axis. Next, it positions the vertical frequency lines and labels on the x axis. Finally, it positions the controls and the curve layer. This method is also called when the orientation of the device changes and the view needs to re-layout for the new view size. */ override func layoutSublayers(of layer: CALayer) { if layer === self.layer { // Disable implicit layer animations. CATransaction.begin() CATransaction.setDisableActions(true) containerLayer.bounds = layer.bounds graphLayer.bounds = CGRect(x: leftMargin, y: bottomMargin, width: layer.bounds.width - leftMargin - rightMargin, height: layer.bounds.height - bottomMargin - 10.0) updateDBLayers() updateFrequencyLayers() editPoint = CGPoint(x: locationForFrequencyValue(frequency), y: locationForDBValue(resonance)) if curveLayer != nil { curveLayer!.bounds = graphLayer.bounds curveLayer!.frame = CGRect(x: graphLayer.frame.origin.x, y: graphLayer.frame.origin.y + bottomMargin, width: graphLayer.frame.width, height: graphLayer.frame.height) } CATransaction.commit() } updateControls(false) frequencies = nil /* Notify view controller that our bounds has changed -- meaning that new frequency data is available. */ delegate?.filterViewDataDidChange(self) } /* If either the frequency or resonance (or both) change, notify the delegate as appropriate. */ func updateFrequenciesAndResonance() { let lastFrequency = frequencyValueForLocation(editPoint.x) let lastResonance = dbValueForLocation(editPoint.y) if (lastFrequency != frequency && lastResonance != resonance) { frequency = lastFrequency resonance = lastResonance // Notify delegate that frequency changed. delegate?.filterView(self, didChangeFrequency: frequency, andResonance: resonance) } if lastFrequency != frequency { frequency = lastFrequency // Notify delegate that frequency changed. delegate?.filterView(self, didChangeFrequency: frequency) } if lastResonance != resonance { resonance = lastResonance // Notify delegate that resonance changed. delegate?.filterView(self, didChangeResonance: resonance) } } // MARK: Touch Event Handling override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { var pointOfTouch = touches.first?.location(in: self) pointOfTouch = CGPoint(x: pointOfTouch!.x, y: pointOfTouch!.y + bottomMargin) if graphLayer.contains(pointOfTouch!) { touchDown = true editPoint = pointOfTouch! updateFrequenciesAndResonance() } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { var pointOfTouch = touches.first?.location(in: self) pointOfTouch = CGPoint(x: pointOfTouch!.x, y: pointOfTouch!.y + bottomMargin) if graphLayer.contains(pointOfTouch!) { processTouch(pointOfTouch!) updateFrequenciesAndResonance() } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { var pointOfTouch = touches.first?.location(in: self) pointOfTouch = CGPoint(x: pointOfTouch!.x, y: pointOfTouch!.y + bottomMargin) if graphLayer.contains(pointOfTouch!) { processTouch(pointOfTouch!) } touchDown = false updateFrequenciesAndResonance() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { touchDown = false } func processTouch(_ touchPoint: CGPoint) { if touchPoint.x < 0 { editPoint.x = 0 } else if touchPoint.x > graphLayer.frame.width + leftMargin { editPoint.x = graphLayer.frame.width + leftMargin } else { editPoint.x = touchPoint.x } if touchPoint.y < 0 { editPoint.y = 0 } else if touchPoint.y > graphLayer.frame.height + bottomMargin { editPoint.y = graphLayer.frame.height + bottomMargin } else { editPoint.y = touchPoint.y } } }
apache-2.0
JakeLin/SwiftWeather
SwiftWeather/Forecast.swift
3
203
// // Created by Jake Lin on 8/26/15. // Copyright © 2015 Jake Lin. All rights reserved. // import Foundation struct Forecast { let time: String let iconText: String let temperature: String }
mit
ejeinc/MetalScope
Examples/StereoVideo/Sources/ViewController.swift
1
5641
// // ViewController.swift // StereoVideo // // Created by Jun Tanaka on 2017/02/06. // Copyright © 2017 eje Inc. All rights reserved. // import UIKit import Metal import MetalScope import AVFoundation final class ViewController: UIViewController { lazy var device: MTLDevice = { guard let device = MTLCreateSystemDefaultDevice() else { fatalError("Failed to create MTLDevice") } return device }() weak var panoramaView: PanoramaView? var player: AVPlayer? var playerLooper: Any? // AVPlayerLopper if available var playerObservingToken: Any? deinit { if let token = playerObservingToken { NotificationCenter.default.removeObserver(token) } } private func loadPanoramaView() { let panoramaView = PanoramaView(frame: view.bounds, device: device) panoramaView.setNeedsResetRotation() panoramaView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(panoramaView) // fill parent view let constraints: [NSLayoutConstraint] = [ panoramaView.topAnchor.constraint(equalTo: view.topAnchor), panoramaView.bottomAnchor.constraint(equalTo: view.bottomAnchor), panoramaView.leadingAnchor.constraint(equalTo: view.leadingAnchor), panoramaView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ] NSLayoutConstraint.activate(constraints) // double tap to reset rotation let doubleTapGestureRecognizer = UITapGestureRecognizer(target: panoramaView, action: #selector(PanoramaView.setNeedsResetRotation(_:))) doubleTapGestureRecognizer.numberOfTapsRequired = 2 panoramaView.addGestureRecognizer(doubleTapGestureRecognizer) // single tap to toggle play/pause let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(togglePlaying)) singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer) panoramaView.addGestureRecognizer(singleTapGestureRecognizer) self.panoramaView = panoramaView } private func loadVideo() { let url = Bundle.main.url(forResource: "Sample", withExtension: "mp4")! let playerItem = AVPlayerItem(url: url) let player = AVQueuePlayer(playerItem: playerItem) panoramaView?.load(player, format: .stereoOverUnder) self.player = player // loop if #available(iOS 10, *) { playerLooper = AVPlayerLooper(player: player, templateItem: playerItem) } else { player.actionAtItemEnd = .none playerObservingToken = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: playerItem, queue: nil) { _ in player.seek(to: kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) } } player.play() } private func loadStereoButton() { let button = UIButton(type: .system) button.setTitle("Stereo", for: .normal) button.addTarget(self, action: #selector(presentStereoView), for: .touchUpInside) button.contentHorizontalAlignment = .right button.contentVerticalAlignment = .bottom button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 16, right: 16) button.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) // place to bottom-right corner let constraints: [NSLayoutConstraint] = [ button.widthAnchor.constraint(equalToConstant: 96), button.heightAnchor.constraint(equalToConstant: 64), button.bottomAnchor.constraint(equalTo: view.bottomAnchor), button.trailingAnchor.constraint(equalTo: view.trailingAnchor) ] NSLayoutConstraint.activate(constraints) } override func viewDidLoad() { super.viewDidLoad() loadPanoramaView() loadVideo() loadStereoButton() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) panoramaView?.isPlaying = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) panoramaView?.isPlaying = false } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) panoramaView?.updateInterfaceOrientation(with: coordinator) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func togglePlaying() { guard let player = player else { return } if player.rate == 0 { player.play() } else { player.pause() } } func presentStereoView() { let introView = UILabel() introView.text = "Place your phone into your Cardboard viewer." introView.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) introView.textAlignment = .center introView.backgroundColor = #colorLiteral(red: 0.2745098039, green: 0.3529411765, blue: 0.3921568627, alpha: 1) let stereoViewController = StereoViewController(device: device) stereoViewController.introductionView = introView stereoViewController.scene = panoramaView?.scene stereoViewController.stereoView.tapGestureRecognizer.addTarget(self, action: #selector(togglePlaying)) present(stereoViewController, animated: true, completion: nil) } }
mit
cheyongzi/MGTV-Swift
MGTV-Swift/Model/Search/SearchResult.swift
1
1672
// // SearchResult.swift // MGTV-Swift // // Created by Che Yongzi on 2016/12/14. // Copyright © 2016年 Che Yongzi. All rights reserved. // import ObjectMapper class SearchFamousInfo: MappableEx { } class SearchResultVideoItem: MappableEx { var name: String? override func mapping(map: Map) { name <- map["name"] } } class SearchResultVideo: MappableEx { var list: [SearchResultVideoItem]? override func mapping(map: Map) { list <- map["list"] } } class SearchResultItem: MappableEx { var playCount: String? var name: String? var image: String? var updateDesc: String? var desc: String? var descPrefix: String? var videoType: String? var layoutId: Int? var videos: [SearchResultVideo]? override func mapping(map: Map) { playCount <- map["playCount"] name <- map["name"] image <- map["image"] updateDesc <- map["updateDesc"] desc <- map["desc"] descPrefix <- map["descPrefix"] videoType <- map["videoType"] layoutId <- map["layoutId"] videos <- map["videos"] } } class SearchResultData: MappableEx { var total: Int? var qcorr: String? var famous: SearchFamousInfo? var hitDocs: [SearchResultItem]? override func mapping(map: Map) { total <- map["total"] qcorr <- map["qcorr"] famous <- map["famous"] hitDocs <- map["hitDocs"] } } class SearchResultResponse: BaseModel { var data: SearchResultData? override func mapping(map: Map) { super.mapping(map: map) data <- map["data"] } }
mit
feliperuzg/CleanExample
CleanExample/Home/View/HomePresenterProtocol.swift
1
287
// // HomePresenterProtocol.swift // CleanExample // // Created by Felipe Ruz on 24-07-17. // Copyright © 2017 Felipe Ruz. All rights reserved. // import Foundation protocol HomePresenterProtocol { func attachView(_ homeView: HomeViewProtocol) func getUserInformation() }
mit
TCA-Team/iOS
TUM Campus App/DataSources/GradesDataSource.swift
1
2753
// // GradesDataSource.swift // Campus // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit class GradesDataSource: NSObject, TUMDataSource, TUMInteractiveDataSource { let parent: CardViewController var manager: PersonalGradeManager let cellType: AnyClass = GradesCollectionViewCell.self var isEmpty: Bool { return data.isEmpty } let cardKey: CardKey = .grades var data: [Grade] = [] var preferredHeight: CGFloat = 228.0 lazy var flowLayoutDelegate: ColumnsFlowLayoutDelegate = FixedColumnsVerticalItemsFlowLayoutDelegate(delegate: self) init(parent: CardViewController, manager: PersonalGradeManager) { self.parent = parent self.manager = manager super.init() } func refresh(group: DispatchGroup) { group.enter() manager.fetch().onSuccess(in: .main) { data in self.data = data group.leave() } } func onShowMore() { let storyboard = UIStoryboard(name: "Grade", bundle: nil) if let destination = storyboard.instantiateInitialViewController() as? GradesTableViewController { destination.delegate = parent destination.values = data parent.navigationController?.pushViewController(destination, animated: true) } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: cellReuseID, for: indexPath) as! GradesCollectionViewCell let grade = data[indexPath.row] cell.gradeLabel.text = grade.result cell.nameLabel.text = grade.name cell.semesterLabel.text = grade.semester cell.gradeLabel.backgroundColor = grade.gradeColor return cell } }
gpl-3.0
bobbymay/HouseAds
Ads/Ad Files/Ads.swift
1
3477
import UIKit /// Wrapper to control everything class Ads: NSObject { static var started = false private static let wall = BannerWall() private static let purchase = AdsPurchase() /// Was in-app purchase used to remove ads static var removed: Bool { return UserDefaults.standard.bool(forKey: "AdsPurchased") } /// In-house banner showing static var showing: Bool { return TopBanner.showing } /// Brings in-house banner to the front of the screen static func bringToFront() { if TopBanner.showing, let topBanner = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5000) { UIApplication.shared.delegate?.window??.rootViewController?.view.bringSubview(toFront: topBanner) } } /// Returns the height of in-house banner static var height: CGFloat { guard TopBanner.showing else { return 0.0 } return TopBanner.height + Screen.statusBarHeight } /// Starts everything static func start() { if !Ads.started { started = true let starts = UserDefaults.standard.integer(forKey: "adStarts") + 1 UserDefaults.standard.set(starts, forKey: ("adStarts")) if Internet.available { Banners.getFile() } else { // if there is no Internet, monitor it, when there is a connection getFile() will be called Internet().monitorInternet() // creates banner if exist if let mb = UserDefaults.standard.dictionary(forKey: "MyBanners") { if !Ads.removed && !TopBanner.created && mb.count > 0 && Banners.count > 0 { _ = TopBanner() } } } } // if changing the orientation is not supported, deleted this and change this class to struct UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(Ads.orientationChanged(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } /// Shows wall of banners static func showWall() { if !BannerWall.showing && Banners.count > 0 { wall.show() } } /** Remove ads by purchase - Parameters: - frame: Frame of button or view that removes ads. This is mostly used for iPad pop-up controller */ static func buy(frame: CGRect) { purchase.removeAds(frame: frame) } /// Ads have been purchased to be removed static func purchased() { UserDefaults.standard.set(true, forKey: "AdsPurchased") if let topBanner = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5000) { topBanner.removeFromSuperview() TopBanner.removed() } if let adsRemoveButton = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5005) { adsRemoveButton.removeFromSuperview() } if let tableRemoveButton = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(8000)?.viewWithTag(8001) { tableRemoveButton.removeFromSuperview() } if BannerWall.showing { BannerWall.resize() } } /// Handles orientation changes (delete if not supported) @objc static func orientationChanged(notification: NSNotification) { if TopBanner.showing, let topBanner = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5000) { topBanner.frame = CGRect.center(x: Screen.width/2, y: topBanner.frame.size.height/2 + Screen.statusBarHeight, width: topBanner.frame.size.width, height: topBanner.frame.size.height) } if BannerWall.showing { BannerWall.resize() } } }
mit
LibraryLoupe/PhotosPlus
PhotosPlus/Cameras/Sony/SonyAlphaSLTA57.swift
3
506
// // Photos Plus, https://github.com/LibraryLoupe/PhotosPlus // // Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved. // import Foundation extension Cameras.Manufacturers.Sony { public struct AlphaSLTA57: CameraModel { public init() {} public let name = "Sony Alpha SLT-A57" public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Sony.self } } public typealias SonyAlphaSLTA57 = Cameras.Manufacturers.Sony.AlphaSLTA57
mit
apegroup/APECountdownView
Source/CountdownNumberView.swift
1
4984
// CountdownNumberView.swift // // The MIT License (MIT) // // Copyright (c) 2016 apegroup // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /** A view with a number and a block. */ @IBDesignable class CountdownNumberView: UIView { /** Label of the number. Do not change this text instead use text property of CountdownNumberView. */ var label: UILabel! /** Color of the first gradient. */ var gradientColor1 = UIColor(red: 0.290, green: 0.290, blue: 0.290, alpha: 1.000) /** Color of the second gradient. */ var gradientColor2 = UIColor(red: 0.153, green: 0.153, blue: 0.153, alpha: 1.000) /** Color of the third gradient. */ var gradientColor3 = UIColor(red: 0.071, green: 0.071, blue: 0.071, alpha: 1.000) /** Color of the fourth gradient. */ var gradientColor4 = UIColor(red: 0.004, green: 0.004, blue: 0.004, alpha: 1.000) private var clipView: UIView! /** The number in the view. */ @IBInspectable var text: String? { didSet { // Only change when it's a new text if label.text == text { return } // Don't animate the first time if label.text != nil { label.slideInFromTop() } label.text = text } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! createSubviews() } override init(frame: CGRect) { super.init(frame: frame) createSubviews() } private func createSubviews() { clipView = UIView() clipView.clipsToBounds = true addSubview(clipView) label = UILabel() label.textColor = UIColor.whiteColor() label.font = UIFont.boldSystemFontOfSize(16) label.textAlignment = NSTextAlignment.Center clipView.addSubview(label) } override func drawRect(rect: CGRect) { // General Declarations let context = UIGraphicsGetCurrentContext() // Gradient Declarations let gradientColors = [gradientColor1.CGColor, gradientColor2.CGColor, gradientColor3.CGColor, gradientColor4.CGColor] let gradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), gradientColors, [0, 0.49, 0.51, 1])! // Shadow Declarations let shadow = NSShadow() shadow.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.3) shadow.shadowOffset = CGSize(width: 0, height: 3) shadow.shadowBlurRadius = 3 // Rectangle Drawing let bezierFrame = CGRect(x: 3, y: 0, width: bounds.size.width - 6, height: bounds.size.height - 6) let rectanglePath = UIBezierPath(roundedRect: bezierFrame, cornerRadius: 5) CGContextSaveGState(context) CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, (shadow.shadowColor as! UIColor).CGColor) CGContextBeginTransparencyLayer(context, nil) rectanglePath.addClip() let gradientPointStart = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMinY(bounds)) let gradientPointEnd = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMaxY(bounds)) CGContextDrawLinearGradient(context, gradient, gradientPointStart, gradientPointEnd, CGGradientDrawingOptions()) CGContextEndTransparencyLayer(context) CGContextRestoreGState(context) } override func layoutSubviews() { super.layoutSubviews() backgroundColor = UIColor.clearColor() let labelFrame = CGRectMake(0, 1, bounds.size.width, bounds.size.height - 9) label.frame = labelFrame clipView.frame = labelFrame } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() text = "0" } }
mit
awsdocs/aws-doc-sdk-examples
swift/example_code/iam/GetRole/Sources/ServiceHandler/ServiceHandler.swift
1
2365
/* A class containing functions that interact with AWS services. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ // snippet-start:[iam.swift.getrole.handler] // snippet-start:[iam.swift.getrole.handler.imports] import Foundation import AWSIAM import ClientRuntime import AWSClientRuntime // snippet-end:[iam.swift.getrole.handler.imports] // snippet-start:[iam.swift.getrole.enum.service-error] /// Errors returned by `ServiceHandler` functions. public enum ServiceHandlerError: Error { case noSuchUser /// No matching user found. case noSuchRole /// No matching role found, or unable to create the role. } // snippet-end:[iam.swift.getrole.enum.service-error] /// A class containing all the code that interacts with the AWS SDK for Swift. public class ServiceHandler { public let client: IamClient /// Initialize and return a new ``ServiceHandler`` object, which is used /// to drive the AWS calls used for the example. The Region string /// `AWS_GLOBAL` is used because users are shared across all Regions. /// /// - Returns: A new ``ServiceHandler`` object, ready to be called to /// execute AWS operations. // snippet-start:[iam.swift.getrole.handler.init] public init() async { do { client = try IamClient(region: "AWS_GLOBAL") } catch { print("ERROR: ", dump(error, name: "Initializing Amazon IAM client")) exit(1) } } // snippet-end:[iam.swift.getrole.handler.init] /// Create a new AWS Identity and Access Management (IAM) role. /// /// - Parameter name: The name of the new IAM role. /// /// - Returns: The ID of the newly created role. // snippet-start:[iam.swift.getrole.handler.getrole] public func getRole(name: String) async throws -> IamClientTypes.Role { let input = GetRoleInput( roleName: name ) do { let output = try await client.getRole(input: input) guard let role = output.role else { throw ServiceHandlerError.noSuchRole } return role } catch { throw error } } // snippet-end:[iam.swift.getrole.handler.getrole] } // snippet-end:[iam.swift.getrole.handler]
apache-2.0
iwheelbuy/VK
VK/Method/Utils/VK+Method+Utils+GetLinkStats.swift
1
3032
//import Foundation // //public extension Method.Utils { // /// Возвращает статистику переходов по сокращенной ссылке. // public struct GetLinkStats { // /// Интервал // public enum Interval: String, Decodable { // /// Час // case hour // /// День // case day // /// Неделя // case week // /// Месяц // case month // /// Все время с момента создания ссылки // case forever // } // /// Ответ // public struct Response: Decodable { // /// Входной параметр key // public let key: String // /// Массив объектов, данные о статистике // public let stats: [Object.ShortenedLinkStats] // } // /// Ключ доступа к приватной статистике // public let access_key: String? // /// Возвращать расширенную статистику (пол/возраст/страна/город) // public let extended: Bool // /// Единица времени для подсчета статистики // public let interval: Method.Utils.GetLinkStats.Interval // /// Длительность периода для получения статистики в выбранных единицах (из параметра interval) // public let intervals_count: UInt // /// Содержательная часть (символы после "vk.cc") // public let key: String // /// Пользовательские данные // public let user: App.User // // public init(access_key: String? = nil, extended: Bool = false, interval: Method.Utils.GetLinkStats.Interval = .day, intervals_count: UInt = 1, key: String, user: App.User) { // self.access_key = access_key // self.extended = extended // self.interval = interval // self.intervals_count = intervals_count // self.key = key // self.user = user // } // } //} // //extension Method.Utils.GetLinkStats: ApiType { // // public var method_name: String { // return "utils.getLinkStats" // } // // public var parameters: [String: String] { // var dictionary = App.parameters // dictionary["access_token"] = user.token // dictionary["access_key"] = access_key // dictionary["interval"] = interval.rawValue // dictionary["intervals_count"] = "\(intervals_count)" // dictionary["extended"] = extended ? "1" : "0" // dictionary["key"] = key // return dictionary // } //} // //extension Method.Utils.GetLinkStats: StrategyType { // // public var api: AnyApi<Method.Utils.GetLinkStats.Response> { // return AnyApi(api: self) // } //}
mit
mactive/rw-courses-note
SwiftUI_12/swiftUI12/swiftUI12Tests/swiftUI12Tests.swift
1
900
// // swiftUI12Tests.swift // swiftUI12Tests // // Created by Qian Meng on 2020/6/30. // import XCTest @testable import swiftUI12 class swiftUI12Tests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
Tricertops/YAML
Sources/Parsing/Parser+Mark.swift
1
2073
// // Parser+Mark.swift // YAML.framework // // Created by Martin Kiss on 14 May 2016. // https://github.com/Tricertops/YAML // // The MIT License (MIT) // Copyright © 2016 Martin Kiss // extension Parser.Mark { func indexInString(_ string: String) -> String.UTF8Index { let start = string.utf8.startIndex let end = string.utf8.endIndex return string.utf8.index(start, offsetBy: Int(self.location), limitedBy: end)! } init(_ mark: yaml_mark_t) { self.location = UInt(mark.index) self.line = UInt(mark.line) self.column = UInt(mark.column) } } extension Parser.Mark: Comparable { } public func == (left: Parser.Mark, right: Parser.Mark) -> Bool { return left.location == right.location } public func < (left: Parser.Mark, right: Parser.Mark) -> Bool { return left.location < right.location } extension Parser.Mark.Range { func rangeInString(_ string: String) -> Swift.Range<String.UTF8Index> { let start = self.start.indexInString(string) let end = self.end.indexInString(string) return start ..< end } func substringFromString(_ string: String) -> String { let range = self.rangeInString(string) return String(string.utf8[range])! } static func union(_ ranges: Parser.Mark.Range? ...) -> Parser.Mark.Range { var start: Parser.Mark? var end: Parser.Mark? for optionalRange in ranges { guard let range = optionalRange else { continue } if start == nil { start = range.start } if end == nil { end = range.end } start = min(start!, range.start) end = max(end!, range.end) } assert(start != nil, "Misuse of range union.") assert(start != nil, "Misuse of range union.") return Parser.Mark.Range(start: start!, end: end!) } } func ... (start: Parser.Mark, end: Parser.Mark) -> Parser.Mark.Range { return Parser.Mark.Range(start: start, end: end) }
mit
samodom/TestableUIKit
TestableUIKit/UIResponder/UIView/UIWebView/UIWebViewGoForwardSpy.swift
1
1679
// // UIWebViewGoForwardSpy.swift // TestableUIKit // // Created by Sam Odom on 2/21/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import UIKit import TestSwagger import FoundationSwagger public extension UIWebView { private static let goForwardCalledKeyString = UUIDKeyString() private static let goForwardCalledKey = ObjectAssociationKey(goForwardCalledKeyString) private static let goForwardCalledReference = SpyEvidenceReference(key: goForwardCalledKey) private static let goForwardCoselectors = SpyCoselectors( methodType: .instance, original: #selector(UIWebView.goForward), spy: #selector(UIWebView.spy_goForward) ) /// Spy controller for ensuring that a web view has had `goForward` called on it. public enum GoForwardSpyController: SpyController { public static let rootSpyableClass: AnyClass = UIWebView.self public static let vector = SpyVector.direct public static let coselectors: Set = [goForwardCoselectors] public static let evidence: Set = [goForwardCalledReference] public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `goForward` dynamic public func spy_goForward() { goForwardCalled = true } /// Indicates whether the `goForward` method has been called on this object. public final var goForwardCalled: Bool { get { return loadEvidence(with: UIWebView.goForwardCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: UIWebView.goForwardCalledReference) } } }
mit
mohamede1945/quran-ios
Quran/TranslationsVersionUpdaterInteractor.swift
2
6530
// // TranslationsVersionUpdaterInteractor.swift // Quran // // Created by Mohamed Afifi on 3/12/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import BatchDownloader import PromiseKit import Zip class TranslationsVersionUpdaterInteractor: Interactor { private let simplePersistence: SimplePersistence private let persistence: ActiveTranslationsPersistence private let downloader: DownloadManager private let versionPersistenceCreator: AnyCreator<String, DatabaseVersionPersistence> init(simplePersistence: SimplePersistence, persistence: ActiveTranslationsPersistence, downloader: DownloadManager, versionPersistenceCreator: AnyCreator<String, DatabaseVersionPersistence>) { self.simplePersistence = simplePersistence self.persistence = persistence self.downloader = downloader self.versionPersistenceCreator = versionPersistenceCreator } func execute(_ translations: [Translation]) -> Promise<[TranslationFull]> { let update = Promise(value: translations) .then(execute: unzipIfNeeded) // unzip if needed .then(execute: updateInstalledVersions) // update versions let downloads = downloader.getOnGoingDownloads() return when(fulfilled: update, downloads) .then(execute: createTranslations) } private func createTranslations(translations: [Translation], downloadsBatches: [DownloadBatchResponse]) -> [TranslationFull] { let downloads = downloadsBatches.filter { $0.isTranslation } let downloadsByFile = downloads.flatGroup { $0.requests.first?.destinationPath.stringByDeletingPathExtension ?? "_" } return translations.map { translation -> TranslationFull in // downloading... let responses = translation.possibleFileNames.flatMap { downloadsByFile[Files.translationsPathComponent.stringByAppendingPath($0.stringByDeletingPathExtension)] } if let response = responses.first { return TranslationFull(translation: translation, response: response) } // not downloaded return TranslationFull(translation: translation, response: nil) } } private func updateInstalledVersions(translations: [Translation]) throws -> [Translation] { var updatedTranslations: [Translation] = [] for var translation in translations { let fileURL = Files.translationsURL.appendingPathComponent(translation.fileName) let isReachable = fileURL.isReachable let previousInstalledVersion = translation.installedVersion // installed on the latest version & the db file exists if translation.version != translation.installedVersion && isReachable { let versionPersistence = versionPersistenceCreator.create(fileURL.absoluteString) do { let version = try versionPersistence.getTextVersion() translation.installedVersion = version } catch { // if an error occurred while getting the version // that means the db file is corrupted. translation.installedVersion = nil } } else if translation.installedVersion != nil && !isReachable { translation.installedVersion = nil } if previousInstalledVersion != translation.installedVersion { try persistence.update(translation) // remove the translation from selected translations if translation.installedVersion == nil { var selectedTranslations = simplePersistence.valueForKey(.selectedTranslations) if let index = selectedTranslations.index(of: translation.id) { selectedTranslations.remove(at: index) simplePersistence.setValue(selectedTranslations, forKey: .selectedTranslations) } } } updatedTranslations.append(translation) } return updatedTranslations } private func unzipIfNeeded(translations: [Translation]) throws -> [Translation] { for translation in translations { // installed on the latest version guard translation.version != translation.installedVersion else { continue } /* states: Is Zip, zip exists , db exists false, x , false // Not Downloaded fasle, x , true // need to check version (might be download/updgrade) true, false , false // Not Downloaded true, false , true // need to check version (might be download/updgrade) true, true , false // Unzip, delete zip, check version true, true , true // Unzip, delete zip, check version | Probably upgrade */ // unzip if needed let raw = translation.rawFileName let isZip = raw.hasSuffix(Files.translationCompressedFileExtension) if isZip { let zipFile = Files.translationsURL.appendingPathComponent(raw) if zipFile.isReachable { // delete the zip in both cases (success or failure) // success: to save space // failure: to redownload it again defer { try? FileManager.default.removeItem(at: zipFile) } try attempt(times: 3) { try Zip.unzipFile(zipFile, destination: Files.translationsURL, overwrite: true, password: nil, progress: nil) } } } } return translations } }
gpl-3.0
swagproject/swag
Sources/View.swift
1
267
// // View.swift // Swag-Test // // Created by Jens Ravens on 24/12/15. // Copyright © 2015 nerdgeschoss GmbH. All rights reserved. // import Foundation public protocol ViewType { func render() throws -> Streamable var contentType: FormatType { get } }
mit
JakeLin/iOSAnimationSample
iOSAnimationSample/SpringViewController.swift
1
1772
// // SpringViewController.swift // iOSAnimationSample // // Created by Jake Lin on 5/5/15. // Copyright (c) 2015 JakeLin. All rights reserved. // import UIKit class SpringViewController: UIViewController { @IBOutlet weak var blueSquare: UIView! @IBOutlet weak var redSquare: UIView! @IBOutlet weak var greenSquare: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(1, animations: { self.blueSquare.center.x = self.view.bounds.width - self.blueSquare.center.x }) UIView.animateWithDuration(5, delay: 0, usingSpringWithDamping: 0.1, initialSpringVelocity: 0, options: [], animations: { self.redSquare.center.x = self.view.bounds.width - self.redSquare.center.x }, completion: nil) UIView.animateWithDuration(5, delay: 0, usingSpringWithDamping: 0.1, initialSpringVelocity: 1, options: [], animations: { self.greenSquare.center.x = self.view.bounds.width - self.greenSquare.center.x }, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
doronkatz/firefox-ios
Storage/Bookmarks/Bookmarks.swift
6
18552
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import Deferred import SwiftyJSON private let log = Logger.syncLogger public protocol SearchableBookmarks: class { func bookmarksByURL(_ url: URL) -> Deferred<Maybe<Cursor<BookmarkItem>>> } public protocol SyncableBookmarks: class, ResettableSyncStorage, AccountRemovalDelegate { // TODO func isUnchanged() -> Deferred<Maybe<Bool>> func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> func treesForEdges() -> Deferred<Maybe<(local: BookmarkTree, buffer: BookmarkTree)>> func treeForMirror() -> Deferred<Maybe<BookmarkTree>> func applyLocalOverrideCompletionOp(_ op: LocalOverrideCompletionOp, itemSources: ItemSources) -> Success } public let NotificationBookmarkBufferValidated = Notification.Name("NotificationBookmarkBufferValidated") public protocol BookmarkBufferStorage: class { func isEmpty() -> Deferred<Maybe<Bool>> func applyRecords(_ records: [BookmarkMirrorItem]) -> Success func doneApplyingRecordsAfterDownload() -> Success func validate() -> Success func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> func applyBufferCompletionOp(_ op: BufferCompletionOp, itemSources: ItemSources) -> Success // Only use for diagnostics. func synchronousBufferCount() -> Int? } public protocol MirrorItemSource: class { func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID } public protocol BufferItemSource: class { func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID } public protocol LocalItemSource: class { func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID } open class ItemSources { open let local: LocalItemSource open let mirror: MirrorItemSource open let buffer: BufferItemSource public init(local: LocalItemSource, mirror: MirrorItemSource, buffer: BufferItemSource) { self.local = local self.mirror = mirror self.buffer = buffer } open func prefetchWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return self.local.prefetchLocalItemsWithGUIDs(guids) >>> { self.mirror.prefetchMirrorItemsWithGUIDs(guids) } >>> { self.buffer.prefetchBufferItemsWithGUIDs(guids) } } } public struct BookmarkRoots { // These match Places on desktop. public static let RootGUID = "root________" public static let MobileFolderGUID = "mobile______" public static let MenuFolderGUID = "menu________" public static let ToolbarFolderGUID = "toolbar_____" public static let UnfiledFolderGUID = "unfiled_____" public static let FakeDesktopFolderGUID = "desktop_____" // Pseudo. Never mentioned in a real record. // This is the order we use. public static let RootChildren: [GUID] = [ BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, BookmarkRoots.MobileFolderGUID, ] public static let DesktopRoots: [GUID] = [ BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, ] public static let Real = Set<GUID>([ BookmarkRoots.RootGUID, BookmarkRoots.MobileFolderGUID, BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, ]) public static let All = Set<GUID>([ BookmarkRoots.RootGUID, BookmarkRoots.MobileFolderGUID, BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, BookmarkRoots.FakeDesktopFolderGUID, ]) /** * Sync records are a horrible mess of Places-native GUIDs and Sync-native IDs. * For example: * {"id":"places", * "type":"folder", * "title":"", * "description":null, * "children":["menu________","toolbar_____", * "tags________","unfiled_____", * "jKnyPDrBQSDg","T6XK5oJMU8ih"], * "parentid":"2hYxKgBwvkEH"}" * * We thus normalize on the extended Places IDs (with underscores) for * local storage, and translate to the Sync IDs when creating an outbound * record. * We translate the record's ID and also its parent. Evidence suggests that * we don't need to translate children IDs. * * TODO: We don't create outbound records yet, so that's why there's no * translation in that direction yet! */ public static func translateIncomingRootGUID(_ guid: GUID) -> GUID { return [ "places": RootGUID, "root": RootGUID, "mobile": MobileFolderGUID, "menu": MenuFolderGUID, "toolbar": ToolbarFolderGUID, "unfiled": UnfiledFolderGUID ][guid] ?? guid } public static func translateOutgoingRootGUID(_ guid: GUID) -> GUID { return [ RootGUID: "places", MobileFolderGUID: "mobile", MenuFolderGUID: "menu", ToolbarFolderGUID: "toolbar", UnfiledFolderGUID: "unfiled" ][guid] ?? guid } /* public static let TagsFolderGUID = "tags________" public static let PinnedFolderGUID = "pinned______" */ static let RootID = 0 static let MobileID = 1 static let MenuID = 2 static let ToolbarID = 3 static let UnfiledID = 4 } /** * This partly matches Places's nsINavBookmarksService, just for sanity. * * It is further extended to support the types that exist in Sync, so we can use * this to store mirrored rows. * * These are only used at the DB layer. */ public enum BookmarkNodeType: Int { case bookmark = 1 case folder = 2 case separator = 3 case dynamicContainer = 4 case livemark = 5 case query = 6 // No microsummary: those turn into bookmarks. } public func == (lhs: BookmarkMirrorItem, rhs: BookmarkMirrorItem) -> Bool { if lhs.type != rhs.type || lhs.guid != rhs.guid || lhs.serverModified != rhs.serverModified || lhs.isDeleted != rhs.isDeleted || lhs.hasDupe != rhs.hasDupe || lhs.pos != rhs.pos || lhs.faviconID != rhs.faviconID || lhs.localModified != rhs.localModified || lhs.parentID != rhs.parentID || lhs.parentName != rhs.parentName || lhs.feedURI != rhs.feedURI || lhs.siteURI != rhs.siteURI || lhs.title != rhs.title || lhs.description != rhs.description || lhs.bookmarkURI != rhs.bookmarkURI || lhs.tags != rhs.tags || lhs.keyword != rhs.keyword || lhs.folderName != rhs.folderName || lhs.queryID != rhs.queryID { return false } if let lhsChildren = lhs.children, let rhsChildren = rhs.children { return lhsChildren == rhsChildren } return lhs.children == nil && rhs.children == nil } public struct BookmarkMirrorItem: Equatable { public let guid: GUID public let type: BookmarkNodeType public var serverModified: Timestamp public let isDeleted: Bool public let hasDupe: Bool public let parentID: GUID? public let parentName: String? // Livemarks. public let feedURI: String? public let siteURI: String? // Separators. let pos: Int? // Folders, livemarks, bookmarks and queries. public let title: String? let description: String? // Bookmarks and queries. let bookmarkURI: String? let tags: String? let keyword: String? // Queries. let folderName: String? let queryID: String? // Folders. public let children: [GUID]? // Internal stuff. let faviconID: Int? public let localModified: Timestamp? let syncStatus: SyncStatus? public func copyWithParentID(_ parentID: GUID, parentName: String?) -> BookmarkMirrorItem { return BookmarkMirrorItem( guid: self.guid, type: self.type, serverModified: self.serverModified, isDeleted: self.isDeleted, hasDupe: self.hasDupe, parentID: parentID, parentName: parentName, feedURI: self.feedURI, siteURI: self.siteURI, pos: self.pos, title: self.title, description: self.description, bookmarkURI: self.bookmarkURI, tags: self.tags, keyword: self.keyword, folderName: self.folderName, queryID: self.queryID, children: self.children, faviconID: self.faviconID, localModified: self.localModified, syncStatus: self.syncStatus) } // Ignores internal metadata and GUID; a pure value comparison. // Does compare child GUIDs! public func sameAs(_ rhs: BookmarkMirrorItem) -> Bool { if self.type != rhs.type || self.isDeleted != rhs.isDeleted || self.pos != rhs.pos || self.parentID != rhs.parentID || self.parentName != rhs.parentName || self.feedURI != rhs.feedURI || self.siteURI != rhs.siteURI || self.title != rhs.title || (self.description ?? "") != (rhs.description ?? "") || self.bookmarkURI != rhs.bookmarkURI || self.tags != rhs.tags || self.keyword != rhs.keyword || self.folderName != rhs.folderName || self.queryID != rhs.queryID { return false } if let lhsChildren = self.children, let rhsChildren = rhs.children { return lhsChildren == rhsChildren } return self.children == nil && rhs.children == nil } public func asJSON() -> JSON { return self.asJSONWithChildren(self.children) } public func asJSONWithChildren(_ children: [GUID]?) -> JSON { var out: [String: Any] = [:] out["id"] = BookmarkRoots.translateOutgoingRootGUID(self.guid) func take(_ key: String, _ val: String?) { guard let val = val else { return } out[key] = val } if self.isDeleted { out["deleted"] = true return JSON(out) } out["hasDupe"] = self.hasDupe // TODO: this should never be nil! if let parentID = self.parentID { out["parentid"] = BookmarkRoots.translateOutgoingRootGUID(parentID) take("parentName", titleForSpecialGUID(parentID) ?? self.parentName ?? "") } func takeBookmarkFields() { take("title", self.title) take("bmkUri", self.bookmarkURI) take("description", self.description) if let tags = self.tags { let tagsJSON = JSON(parseJSON: tags) if let tagsArray = tagsJSON.array, tagsArray.every({ $0.type == SwiftyJSON.Type.string }) { out["tags"] = tagsArray } else { out["tags"] = [] } } else { out["tags"] = [] } take("keyword", self.keyword) } func takeFolderFields() { take("title", titleForSpecialGUID(self.guid) ?? self.title) take("description", self.description) if let children = children { if BookmarkRoots.RootGUID == self.guid { // Only the root contains roots, and so only its children // need to be translated. out["children"] = children.map(BookmarkRoots.translateOutgoingRootGUID) } else { out["children"] = children } } } switch self.type { case .query: out["type"] = "query" take("folderName", self.folderName) take("queryId", self.queryID) takeBookmarkFields() case .bookmark: out["type"] = "bookmark" takeBookmarkFields() case .livemark: out["type"] = "livemark" take("siteUri", self.siteURI) take("feedUri", self.feedURI) takeFolderFields() case .folder: out["type"] = "folder" takeFolderFields() case .separator: out["type"] = "separator" if let pos = self.pos { out["pos"] = pos } case .dynamicContainer: // Sigh. preconditionFailure("DynamicContainer not supported.") } return JSON(out) } // The places root is a folder but has no parentName. public static func folder(_ guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, children: [GUID]) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .folder, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: children, faviconID: nil, localModified: nil, syncStatus: nil) } public static func livemark(_ guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String?, description: String?, feedURI: String, siteURI: String) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .livemark, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: feedURI, siteURI: siteURI, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func separator(_ guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, pos: Int) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .separator, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: pos, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func bookmark(_ guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, URI: String, tags: String, keyword: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .bookmark, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func query(_ guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, URI: String, tags: String, keyword: String?, folderName: String?, queryID: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .query, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: folderName, queryID: queryID, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func deleted(_ type: BookmarkNodeType, guid: GUID, modified: Timestamp) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) return BookmarkMirrorItem(guid: id, type: type, serverModified: modified, isDeleted: true, hasDupe: false, parentID: nil, parentName: nil, feedURI: nil, siteURI: nil, pos: nil, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } }
mpl-2.0
xedin/swift
stdlib/public/core/UnicodeHelpers.swift
2
13165
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Low-level helper functions and utilities for interpreting Unicode // @inlinable @inline(__always) internal func _decodeUTF8(_ x: UInt8) -> Unicode.Scalar { _internalInvariant(UTF8.isASCII(x)) return Unicode.Scalar(_unchecked: UInt32(x)) } @inlinable @inline(__always) internal func _decodeUTF8(_ x: UInt8, _ y: UInt8) -> Unicode.Scalar { _internalInvariant(_utf8ScalarLength(x) == 2) _internalInvariant(UTF8.isContinuation(y)) let x = UInt32(x) let value = ((x & 0b0001_1111) &<< 6) | _continuationPayload(y) return Unicode.Scalar(_unchecked: value) } @inlinable @inline(__always) internal func _decodeUTF8( _ x: UInt8, _ y: UInt8, _ z: UInt8 ) -> Unicode.Scalar { _internalInvariant(_utf8ScalarLength(x) == 3) _internalInvariant(UTF8.isContinuation(y) && UTF8.isContinuation(z)) let x = UInt32(x) let value = ((x & 0b0000_1111) &<< 12) | (_continuationPayload(y) &<< 6) | _continuationPayload(z) return Unicode.Scalar(_unchecked: value) } @inlinable @inline(__always) internal func _decodeUTF8( _ x: UInt8, _ y: UInt8, _ z: UInt8, _ w: UInt8 ) -> Unicode.Scalar { _internalInvariant(_utf8ScalarLength(x) == 4) _internalInvariant( UTF8.isContinuation(y) && UTF8.isContinuation(z) && UTF8.isContinuation(w)) let x = UInt32(x) let value = ((x & 0b0000_1111) &<< 18) | (_continuationPayload(y) &<< 12) | (_continuationPayload(z) &<< 6) | _continuationPayload(w) return Unicode.Scalar(_unchecked: value) } internal func _decodeScalar( _ utf16: UnsafeBufferPointer<UInt16>, startingAt i: Int ) -> (Unicode.Scalar, scalarLength: Int) { let high = utf16[i] if i + 1 >= utf16.count { _internalInvariant(!UTF16.isLeadSurrogate(high)) _internalInvariant(!UTF16.isTrailSurrogate(high)) return (Unicode.Scalar(_unchecked: UInt32(high)), 1) } if !UTF16.isLeadSurrogate(high) { _internalInvariant(!UTF16.isTrailSurrogate(high)) return (Unicode.Scalar(_unchecked: UInt32(high)), 1) } let low = utf16[i+1] _internalInvariant(UTF16.isLeadSurrogate(high)) _internalInvariant(UTF16.isTrailSurrogate(low)) return (UTF16._decodeSurrogates(high, low), 2) } @inlinable internal func _decodeScalar( _ utf8: UnsafeBufferPointer<UInt8>, startingAt i: Int ) -> (Unicode.Scalar, scalarLength: Int) { let cu0 = utf8[_unchecked: i] let len = _utf8ScalarLength(cu0) switch len { case 1: return (_decodeUTF8(cu0), len) case 2: return (_decodeUTF8(cu0, utf8[_unchecked: i &+ 1]), len) case 3: return (_decodeUTF8( cu0, utf8[_unchecked: i &+ 1], utf8[_unchecked: i &+ 2]), len) case 4: return (_decodeUTF8( cu0, utf8[_unchecked: i &+ 1], utf8[_unchecked: i &+ 2], utf8[_unchecked: i &+ 3]), len) default: Builtin.unreachable() } } @inlinable internal func _decodeScalar( _ utf8: UnsafeBufferPointer<UInt8>, endingAt i: Int ) -> (Unicode.Scalar, scalarLength: Int) { let len = _utf8ScalarLength(utf8, endingAt: i) let (scalar, scalarLen) = _decodeScalar(utf8, startingAt: i &- len) _internalInvariant(len == scalarLen) return (scalar, len) } @inlinable @inline(__always) internal func _utf8ScalarLength(_ x: UInt8) -> Int { _internalInvariant(!UTF8.isContinuation(x)) if UTF8.isASCII(x) { return 1 } // TODO(String micro-performance): check codegen return (~x).leadingZeroBitCount } @inlinable @inline(__always) internal func _utf8ScalarLength( _ utf8: UnsafeBufferPointer<UInt8>, endingAt i: Int ) -> Int { var len = 1 while UTF8.isContinuation(utf8[_unchecked: i &- len]) { len &+= 1 } _internalInvariant(len == _utf8ScalarLength(utf8[i &- len])) return len } @inlinable @inline(__always) internal func _continuationPayload(_ x: UInt8) -> UInt32 { return UInt32(x & 0x3F) } @inlinable @inline(__always) internal func _scalarAlign( _ utf8: UnsafeBufferPointer<UInt8>, _ idx: Int ) -> Int { var i = idx while _slowPath(UTF8.isContinuation(utf8[_unchecked: i])) { i &-= 1 _internalInvariant(i >= 0, "Malformed contents: starts with continuation byte") } return i } // // Scalar helpers // extension _StringGuts { @inlinable @inline(__always) // fast-path: fold common fastUTF8 check internal func scalarAlign(_ idx: Index) -> Index { // TODO(String performance): isASCII check if _slowPath(idx.transcodedOffset != 0 || idx._encodedOffset == 0) { // Transcoded indices are already scalar aligned return String.Index(_encodedOffset: idx._encodedOffset) } if _slowPath(self.isForeign) { return foreignScalarAlign(idx) } return self.withFastUTF8 { utf8 in let i = _scalarAlign(utf8, idx._encodedOffset) // If no alignment is performed, keep grapheme cache if i == idx._encodedOffset { return idx } return Index(_encodedOffset: i) } } @inlinable internal func fastUTF8ScalarLength(startingAt i: Int) -> Int { _internalInvariant(isFastUTF8) let len = _utf8ScalarLength(self.withFastUTF8 { $0[i] }) _internalInvariant((1...4) ~= len) return len } @inlinable internal func fastUTF8ScalarLength(endingAt i: Int) -> Int { _internalInvariant(isFastUTF8) return self.withFastUTF8 { utf8 in _internalInvariant(i == utf8.count || !UTF8.isContinuation(utf8[i])) var len = 1 while UTF8.isContinuation(utf8[i &- len]) { _internalInvariant(i &- len > 0) len += 1 } _internalInvariant(len <= 4) return len } } @inlinable internal func fastUTF8Scalar(startingAt i: Int) -> Unicode.Scalar { _internalInvariant(isFastUTF8) return self.withFastUTF8 { _decodeScalar($0, startingAt: i).0 } } @usableFromInline @_effects(releasenone) internal func isOnUnicodeScalarBoundary(_ i: String.Index) -> Bool { // TODO(String micro-performance): check isASCII // Beginning and end are always scalar aligned; mid-scalar never is guard i.transcodedOffset == 0 else { return false } if i == self.startIndex || i == self.endIndex { return true } if _fastPath(isFastUTF8) { return self.withFastUTF8 { return !UTF8.isContinuation($0[i._encodedOffset]) } } return i == foreignScalarAlign(i) } } // // Error-correcting helpers (U+FFFD for unpaired surrogates) for accessing // contents of foreign strings // extension _StringGuts { @_effects(releasenone) private func _getForeignCodeUnit(at i: Int) -> UInt16 { #if _runtime(_ObjC) // Currently, foreign means NSString return _cocoaStringSubscript(_object.cocoaObject, i) #else fatalError("No foreign strings on Linux in this version of Swift") #endif } @usableFromInline @_effects(releasenone) internal func foreignErrorCorrectedScalar( startingAt idx: String.Index ) -> (Unicode.Scalar, scalarLength: Int) { _internalInvariant(idx.transcodedOffset == 0) _internalInvariant(idx._encodedOffset < self.count) let start = idx._encodedOffset let leading = _getForeignCodeUnit(at: start) if _fastPath(!UTF16.isSurrogate(leading)) { return (Unicode.Scalar(_unchecked: UInt32(leading)), 1) } // Validate foreign strings on-read: trailing surrogates are invalid, // leading need following trailing // // TODO(String performance): Consider having a valid performance flag // available to check, and assert it's not set in the condition here. let nextOffset = start &+ 1 if _slowPath(UTF16.isTrailSurrogate(leading) || nextOffset == self.count) { return (Unicode.Scalar._replacementCharacter, 1) } let trailing = _getForeignCodeUnit(at: nextOffset) if _slowPath(!UTF16.isTrailSurrogate(trailing)) { return (Unicode.Scalar._replacementCharacter, 1) } return (UTF16._decodeSurrogates(leading, trailing), 2) } @_effects(releasenone) internal func foreignErrorCorrectedScalar( endingAt idx: String.Index ) -> (Unicode.Scalar, scalarLength: Int) { _internalInvariant(idx.transcodedOffset == 0) _internalInvariant(idx._encodedOffset <= self.count) _internalInvariant(idx._encodedOffset > 0) let end = idx._encodedOffset let trailing = _getForeignCodeUnit(at: end &- 1) if _fastPath(!UTF16.isSurrogate(trailing)) { return (Unicode.Scalar(_unchecked: UInt32(trailing)), 1) } // Validate foreign strings on-read: trailing surrogates are invalid, // leading need following trailing // // TODO(String performance): Consider having a valid performance flag // available to check, and assert it's not set in the condition here. let priorOffset = end &- 2 if _slowPath(UTF16.isLeadSurrogate(trailing) || priorOffset < 0) { return (Unicode.Scalar._replacementCharacter, 1) } let leading = _getForeignCodeUnit(at: priorOffset) if _slowPath(!UTF16.isLeadSurrogate(leading)) { return (Unicode.Scalar._replacementCharacter, 1) } return (UTF16._decodeSurrogates(leading, trailing), 2) } @_effects(releasenone) internal func foreignErrorCorrectedUTF16CodeUnit( at idx: String.Index ) -> UInt16 { _internalInvariant(idx.transcodedOffset == 0) _internalInvariant(idx._encodedOffset < self.count) let start = idx._encodedOffset let cu = _getForeignCodeUnit(at: start) if _fastPath(!UTF16.isSurrogate(cu)) { return cu } // Validate foreign strings on-read: trailing surrogates are invalid, // leading need following trailing // // TODO(String performance): Consider having a valid performance flag // available to check, and assert it's not set in the condition here. if UTF16.isLeadSurrogate(cu) { let nextOffset = start &+ 1 guard nextOffset < self.count, UTF16.isTrailSurrogate(_getForeignCodeUnit(at: nextOffset)) else { return UTF16._replacementCodeUnit } } else { let priorOffset = start &- 1 guard priorOffset >= 0, UTF16.isLeadSurrogate(_getForeignCodeUnit(at: priorOffset)) else { return UTF16._replacementCodeUnit } } return cu } @usableFromInline @inline(never) // slow-path @_effects(releasenone) internal func foreignScalarAlign(_ idx: Index) -> Index { _internalInvariant(idx._encodedOffset < self.count) let ecCU = foreignErrorCorrectedUTF16CodeUnit(at: idx) if _fastPath(!UTF16.isTrailSurrogate(ecCU)) { return idx } _internalInvariant(idx._encodedOffset > 0, "Error-correction shouldn't give trailing surrogate at position zero") return String.Index(_encodedOffset: idx._encodedOffset &- 1) } @usableFromInline @inline(never) @_effects(releasenone) internal func foreignErrorCorrectedGrapheme( startingAt start: Int, endingAt end: Int ) -> Character { #if _runtime(_ObjC) _internalInvariant(self.isForeign) // Both a fast-path for single-code-unit graphemes and validation: // ICU treats isolated surrogates as isolated graphemes let count = end &- start if start &- end == 1 { return Character(String(self.foreignErrorCorrectedScalar( startingAt: String.Index(_encodedOffset: start) ).0)) } // TODO(String performance): Stack buffer if small enough var cus = Array<UInt16>(repeating: 0, count: count) cus.withUnsafeMutableBufferPointer { _cocoaStringCopyCharacters( from: self._object.cocoaObject, range: start..<end, into: $0.baseAddress._unsafelyUnwrappedUnchecked) } return cus.withUnsafeBufferPointer { return Character(String._uncheckedFromUTF16($0)) } #else fatalError("No foreign strings on Linux in this version of Swift") #endif } } // Higher level aggregate operations. These should only be called when the // result is the sole operation done by a caller, otherwise it's always more // efficient to use `withFastUTF8` in the caller. extension _StringGuts { @inlinable @inline(__always) internal func errorCorrectedScalar( startingAt i: Int ) -> (Unicode.Scalar, scalarLength: Int) { if _fastPath(isFastUTF8) { return withFastUTF8 { _decodeScalar($0, startingAt: i) } } return foreignErrorCorrectedScalar( startingAt: String.Index(_encodedOffset: i)) } @inlinable @inline(__always) internal func errorCorrectedCharacter( startingAt start: Int, endingAt end: Int ) -> Character { if _fastPath(isFastUTF8) { return withFastUTF8(range: start..<end) { utf8 in return Character(unchecked: String._uncheckedFromUTF8(utf8)) } } return foreignErrorCorrectedGrapheme(startingAt: start, endingAt: end) } }
apache-2.0
HabitRPG/habitrpg-ios
Habitica Models/Habitica Models/User/EmailNotificationsProtocol.swift
1
726
// // EmailNotificationsProtocol.swift // Habitica Models // // Created by Phillip Thelen on 05.02.20. // Copyright © 2020 HabitRPG Inc. All rights reserved. // import Foundation @objc public protocol EmailNotificationsProtocol { var giftedGems: Bool { get set } var giftedSubscription: Bool { get set } var invitedGuild: Bool { get set } var invitedParty: Bool { get set } var invitedQuest: Bool { get set } var hasNewPM: Bool { get set } var questStarted: Bool { get set } var wonChallenge: Bool { get set } var majorUpdates: Bool { get set } var unsubscribeFromAll: Bool { get set } var kickedGroup: Bool { get set } var subscriptionReminders: Bool { get set } }
gpl-3.0
devxoul/URLNavigator
Example/Sources/Navigator/NavigationMap.swift
1
1841
// // NavigationMap.swift // URLNavigatorExample // // Created by Suyeol Jeon on 7/12/16. // Copyright © 2016 Suyeol Jeon. All rights reserved. // import SafariServices import UIKit import URLNavigator enum NavigationMap { static func initialize(navigator: NavigatorProtocol) { navigator.register("navigator://user/<username>") { url, values, context in guard let username = values["username"] as? String else { return nil } return UserViewController(navigator: navigator, username: username) } navigator.register("http://<path:_>", self.webViewControllerFactory) navigator.register("https://<path:_>", self.webViewControllerFactory) navigator.handle("navigator://alert", self.alert(navigator: navigator)) navigator.handle("navigator://<path:_>") { (url, values, context) -> Bool in // No navigator match, do analytics or fallback function here print("[Navigator] NavigationMap.\(#function):\(#line) - global fallback function is called") return true } } private static func webViewControllerFactory( url: URLConvertible, values: [String: Any], context: Any? ) -> UIViewController? { guard let url = url.urlValue else { return nil } return SFSafariViewController(url: url) } private static func alert(navigator: NavigatorProtocol) -> URLOpenHandlerFactory { return { url, values, context in guard let title = url.queryParameters["title"] else { return false } let message = url.queryParameters["message"] let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) navigator.present(alertController, wrap: nil, from: nil, animated: true, completion: nil) return true } } }
mit
RevenueCat/purchases-ios
Tests/UnitTests/SubscriberAttributes/AttributionDataMigratorTests.swift
1
42052
import Nimble import StoreKit import XCTest @testable import RevenueCat // swiftlint:disable identifier_name class AttributionDataMigratorTests: TestCase { static let defaultIdfa = "00000000-0000-0000-0000-000000000000" static let defaultIdfv = "A9CFE78C-51F8-4808-94FD-56B4535753C6" static let defaultIp = "192.168.1.130" static let defaultNetworkId = "20f0c0000aca0b00000fb0000c0f0f00" static let defaultRCNetworkId = "10f0c0000aca0b00000fb0000c0f0f00" var attributionDataMigrator: AttributionDataMigrator! override func setUp() { super.setUp() attributionDataMigrator = AttributionDataMigrator() } func testAdjustAttributionIsConverted() { let adjustData = adjustData() let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: adjustData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.adjustID.key: AttributionKey.Adjust.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.Adjust.network.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.Adjust.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.Adjust.adGroup.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.Adjust.creative.rawValue ] checkConvertedAttributes(converted: converted, original: adjustData, expectedMapping: expectedMapping) } func testAdjustAttributionConversionDiscardsNSNullValues() { let adjustData = adjustData( withIdfa: .nsNull, adjustId: .nsNull, networkID: .nsNull, idfv: .nsNull, ip: .nsNull, campaign: .nsNull, adGroup: .nsNull, creative: .nsNull, network: .nsNull ) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: adjustData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) == 0 } func testAdjustAttributionConversionGivesPreferenceToAdIdOverRCNetworkID() { let adjustData = adjustData(adjustId: .defaultValue, networkID: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: adjustData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.adjustID.key: AttributionKey.Adjust.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.Adjust.network.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.Adjust.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.Adjust.adGroup.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.Adjust.creative.rawValue ] checkConvertedAttributes(converted: converted, original: adjustData, expectedMapping: expectedMapping) } func testAdjustAttributionConversionRemovesNSNullRCNetworkID() { let adjustData = adjustData(adjustId: .notPresent, networkID: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: adjustData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) != 0 expect(converted[ReservedSubscriberAttribute.adjustID.key]).to(beNil()) } func testAdjustAttributionConversionDiscardsRCNetworkIDCorrectly() { let adjustData = adjustData(adjustId: .notPresent, networkID: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: adjustData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) != 0 expect(converted[ReservedSubscriberAttribute.adjustID.key]).to(beNil()) } func testAdjustAttributionConversionWorksIfStandardKeysAreNotPassed() { let adjustData = adjustData( withIdfa: .notPresent, adjustId: .notPresent, networkID: .notPresent, idfv: .notPresent, ip: .notPresent, campaign: .notPresent, adGroup: .notPresent, creative: .notPresent, network: .notPresent ) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: adjustData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) == 0 } func testAppsFlyerAttributionIsProperlyConverted() { let appsFlyerData = appsFlyerData() let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.AppsFlyer.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.AppsFlyer.adSet.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue, ReservedSubscriberAttribute.keyword.key: AttributionKey.AppsFlyer.adKeywords.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.AppsFlyer.adId.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionDiscardsNSNullValues() { let appsFlyerData = appsFlyerData( withIDFA: .nsNull, appsFlyerId: .nsNull, networkID: .nsNull, idfv: .nsNull, channel: .nsNull, mediaSource: .nsNull, adKey: .nsNull, adGroup: .nsNull, adId: .nsNull, campaign: .nsNull, adSet: .nsNull, adKeywords: .nsNull, ip: .nsNull ) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) == 0 } func testAppsFlyerAttributionConversionGivesPreferenceToAdIdOverRCNetworkID() { let appsFlyerData = appsFlyerData(appsFlyerId: .defaultValue, networkID: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.AppsFlyer.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.AppsFlyer.adSet.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue, ReservedSubscriberAttribute.keyword.key: AttributionKey.AppsFlyer.adKeywords.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.AppsFlyer.adId.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionConversionRemovesNSNullRCNetworkID() { let appsFlyerData = appsFlyerData(appsFlyerId: .notPresent, networkID: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 expect(converted[ReservedSubscriberAttribute.appsFlyerID.key]).to(beNil()) } func testAppsFlyerAttributionConversionUsesRCNetworkIDIfNoAppsFlyerID() { let appsFlyerData = appsFlyerData(appsFlyerId: .notPresent, networkID: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.networkID.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.AppsFlyer.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.AppsFlyer.adSet.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue, ReservedSubscriberAttribute.keyword.key: AttributionKey.AppsFlyer.adKeywords.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.AppsFlyer.adId.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionConversionWorksIfStandardKeysAreNotPassed() { let appsFlyerData = appsFlyerData( withIDFA: .notPresent, appsFlyerId: .notPresent, networkID: .notPresent, idfv: .notPresent, channel: .notPresent, mediaSource: .notPresent, adKey: .notPresent, adGroup: .notPresent, adId: .notPresent, campaign: .notPresent, adSet: .notPresent, adKeywords: .notPresent, ip: .notPresent ) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) == 0 } func testAppsFlyerAttributionConvertsMediaSourceAttribution() { let appsFlyerData = appsFlyerData(channel: .notPresent, mediaSource: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.mediaSource.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionConvertsMediaSourceIfChannelIsNSNull() { let appsFlyerData = appsFlyerData(channel: .nsNull, mediaSource: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.mediaSource.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionGivesPreferenceToChannelOverMediaSourceWhenConvertingMediaSourceSubscriberAttribute() { let appsFlyerData = appsFlyerData(channel: .defaultValue, mediaSource: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerConversionUsesChannelAsMediaSourceSubscriberAttributeIfThereIsNoMediaSourceAttribution() { let appsFlyerData = appsFlyerData(channel: .defaultValue, mediaSource: .notPresent) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerConversionUsesChannelAsMediaSourceSubscriberAttributeIfMediaSourceAttributionIsNSNull() { let appsFlyerData = appsFlyerData(channel: .defaultValue, mediaSource: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionConvertsAdGroupAttribution() { let appsFlyerData = appsFlyerData(adKey: .notPresent, adGroup: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.adGroup.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionConvertsAdGroupIfAdIsNSNull() { let appsFlyerData = appsFlyerData(adKey: .nsNull, adGroup: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.adGroup.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } // swiftlint:disable:next line_length func testAppsFlyerAttributionGivesPreferenceToAdIfThereIsAdAndAdGroupAttributionWhenConvertingAdSubscriberAttribute() { let appsFlyerData = appsFlyerData(adKey: .defaultValue, adGroup: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerConversionUsesAdAsAdSubscriberAttributeIfThereIsNoAdGroupAttribution() { let appsFlyerData = appsFlyerData(adKey: .defaultValue, adGroup: .notPresent) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerConversionUsesAdSubscriberAttributeIfAdGroupAttributionIsNSNull() { let appsFlyerData = appsFlyerData(adKey: .defaultValue, adGroup: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionIsProperlyConvertedIfInsideDataKeyInDictionary() { var appsFlyerDataWithInnerJSON: [String: Any] = ["status": 1] let appsFlyerData: [String: Any] = appsFlyerData() var appsFlyerDataClean: [String: Any] = [:] for (key, value) in appsFlyerData { if key.starts(with: "rc_") { appsFlyerDataWithInnerJSON[key] = value } else { appsFlyerDataClean[key] = value } } appsFlyerDataWithInnerJSON["data"] = appsFlyerDataClean let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.AppsFlyer.id.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.AppsFlyer.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.AppsFlyer.adSet.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue, ReservedSubscriberAttribute.keyword.key: AttributionKey.AppsFlyer.adKeywords.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.AppsFlyer.adId.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionIsProperlyConvertedIfInsideDataKeyInDictionaryAndRCNetworkID() { var appsFlyerDataWithInnerJSON: [String: Any] = ["status": 1] let appsFlyerData: [String: Any] = appsFlyerData(appsFlyerId: .notPresent, networkID: .defaultValue) var appsFlyerDataClean: [String: Any] = [:] for (key, value) in appsFlyerData { if key.starts(with: "rc_") { appsFlyerDataWithInnerJSON[key] = value } else { appsFlyerDataClean[key] = value } } appsFlyerDataWithInnerJSON["data"] = appsFlyerDataClean let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.networkID.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.AppsFlyer.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.AppsFlyer.adSet.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue, ReservedSubscriberAttribute.keyword.key: AttributionKey.AppsFlyer.adKeywords.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.AppsFlyer.adId.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testAppsFlyerAttributionIsProperlyConvertedIfInsideDataKeyInDictionaryAndAndAppsFlyerIsNull() { var appsFlyerDataWithInnerJSON: [String: Any] = ["status": 1] let appsFlyerData: [String: Any] = appsFlyerData(appsFlyerId: .nsNull, networkID: .defaultValue) var appsFlyerDataClean: [String: Any] = [:] for (key, value) in appsFlyerData { if key.starts(with: "rc_") { appsFlyerDataWithInnerJSON[key] = value } else { appsFlyerDataClean[key] = value } } appsFlyerDataWithInnerJSON["data"] = appsFlyerDataClean let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: appsFlyerData, network: AttributionNetwork.appsFlyer.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.appsFlyerID.key: AttributionKey.networkID.rawValue, ReservedSubscriberAttribute.mediaSource.key: AttributionKey.AppsFlyer.channel.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.AppsFlyer.campaign.rawValue, ReservedSubscriberAttribute.adGroup.key: AttributionKey.AppsFlyer.adSet.rawValue, ReservedSubscriberAttribute.ad.key: AttributionKey.AppsFlyer.ad.rawValue, ReservedSubscriberAttribute.keyword.key: AttributionKey.AppsFlyer.adKeywords.rawValue, ReservedSubscriberAttribute.creative.key: AttributionKey.AppsFlyer.adId.rawValue ] checkConvertedAttributes(converted: converted, original: appsFlyerData, expectedMapping: expectedMapping) } func testBranchAttributionIsConverted() { let branchData = branchData() let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: branchData, network: AttributionNetwork.branch.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.mediaSource.key: AttributionKey.Branch.channel.rawValue, ReservedSubscriberAttribute.campaign.key: AttributionKey.Branch.campaign.rawValue ] checkConvertedAttributes(converted: converted, original: branchData, expectedMapping: expectedMapping) } func testBranchAttributionConversionDiscardsNSNullValues() { let branchData = branchData(withIDFA: .nsNull, idfv: .nsNull, ip: .nsNull, channel: .nsNull, campaign: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: branchData, network: AttributionNetwork.branch.rawValue) expect(converted.count) == 0 } func testBranchAttributionConversionWorksIfStandardKeysAreNotPassed() { let branchData = branchData(withIDFA: .notPresent, idfv: .notPresent, ip: .notPresent, channel: .notPresent, campaign: .notPresent) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: branchData, network: AttributionNetwork.branch.rawValue) expect(converted.count) == 0 } func testTenjinAttributionIsConverted() { let tenjinData = facebookOrTenjinData() let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: tenjinData, network: AttributionNetwork.tenjin.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) } func testTenjinAttributionConversionDiscardsNSNullValues() { let tenjinData = facebookOrTenjinData(withIDFA: .nsNull, idfv: .nsNull, ip: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: tenjinData, network: AttributionNetwork.tenjin.rawValue) expect(converted.count) == 0 } func testTenjinAttributionConversionWorksIfStandardKeysAreNotPassed() { let tenjinData = facebookOrTenjinData(withIDFA: .notPresent, idfv: .notPresent, ip: .notPresent) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: tenjinData, network: AttributionNetwork.tenjin.rawValue) expect(converted.count) == 0 } func testFacebookAttributionIsConverted() { let facebookData = facebookOrTenjinData() let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: facebookData, network: AttributionNetwork.facebook.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) } func testFacebookAttributionConversionDiscardsNSNullValues() { let facebookData = facebookOrTenjinData(withIDFA: .nsNull, idfv: .nsNull, ip: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: facebookData, network: AttributionNetwork.facebook.rawValue) expect(converted.count) == 0 } func testFacebookAttributionConversionWorksIfStandardKeysAreNotPassed() { let facebookData = facebookOrTenjinData(withIDFA: .notPresent, idfv: .notPresent, ip: .notPresent) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: facebookData, network: AttributionNetwork.facebook.rawValue) expect(converted.count) == 0 } func testMParticleAttributionIsConverted() { let mparticleData = mParticleData() let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: mparticleData, network: AttributionNetwork.mParticle.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.mpParticleID.key: AttributionKey.MParticle.id.rawValue ] checkConvertedAttributes(converted: converted, original: mparticleData, expectedMapping: expectedMapping) } func testMParticleAttributionConversionDiscardsNSNullValues() { let mparticleData = mParticleData(withIDFA: .nsNull, idfv: .nsNull, mParticleId: .nsNull, networkID: .nsNull, ip: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: mparticleData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) == 0 } func testMParticleAttributionConversionGivesPreferenceToRCNetworkIDOverMParticleId() { let mparticleData = mParticleData(mParticleId: .defaultValue, networkID: .defaultValue) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: mparticleData, network: AttributionNetwork.mParticle.rawValue) expect(converted.count) != 0 checkCommonAttributes(in: converted) let expectedMapping = [ ReservedSubscriberAttribute.mpParticleID.key: AttributionKey.networkID.rawValue ] checkConvertedAttributes(converted: converted, original: mparticleData, expectedMapping: expectedMapping) } func testMParticleAttributionConversionRemovesNSNullRCNetworkID() { let mparticleData = mParticleData(mParticleId: .notPresent, networkID: .nsNull) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: mparticleData, network: AttributionNetwork.mParticle.rawValue) expect(converted.count) != 0 expect(converted[ReservedSubscriberAttribute.mpParticleID.key]).to(beNil()) } func testMParticleAttributionConversionUsesMParticleIDIfNoRCNetworkID() { let mparticleData = mParticleData(mParticleId: .defaultValue, networkID: .notPresent) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: mparticleData, network: AttributionNetwork.mParticle.rawValue) expect(converted.count) != 0 let expectedMapping = [ ReservedSubscriberAttribute.mpParticleID.key: AttributionKey.MParticle.id.rawValue ] checkConvertedAttributes(converted: converted, original: mparticleData, expectedMapping: expectedMapping) } func testMParticleAttributionConversionWorksIfStandardKeysAreNotPassed() { let mparticleData = mParticleData(withIDFA: .notPresent, idfv: .notPresent, mParticleId: .notPresent, networkID: .notPresent, ip: .notPresent) let converted = attributionDataMigrator.convertToSubscriberAttributes( attributionData: mparticleData, network: AttributionNetwork.adjust.rawValue) expect(converted.count) == 0 } } private enum KeyPresence { case defaultValue, nsNull, notPresent } private extension AttributionDataMigratorTests { func checkConvertedAttributes( converted: [String: Any], original: [String: Any], expectedMapping: [String: String] ) { for (subscriberAttribute, attributionKey) in expectedMapping { expect((converted[subscriberAttribute] as? String)) == (original[attributionKey] as? String) } } func checkCommonAttributes(in converted: [String: Any], idfa: KeyPresence = .defaultValue, idfv: KeyPresence = .defaultValue, ip: KeyPresence = .defaultValue) { let idfaValue = converted[ReservedSubscriberAttribute.idfa.key] switch idfa { case .defaultValue: expect(idfaValue as? String) == AttributionDataMigratorTests.defaultIdfa case .nsNull: expect(idfaValue).to(beAKindOf(NSNull.self)) case .notPresent: expect(idfaValue).to(beNil()) } let idfvValue = converted[ReservedSubscriberAttribute.idfv.key] switch idfv { case .defaultValue: expect(idfvValue as? String) == AttributionDataMigratorTests.defaultIdfv case .nsNull: expect(idfvValue).to(beAKindOf(NSNull.self)) case .notPresent: expect(idfvValue).to(beNil()) } let ipValue = converted[ReservedSubscriberAttribute.ip.key] switch ip { case .defaultValue: expect(ipValue as? String) == AttributionDataMigratorTests.defaultIp case .nsNull: expect(ipValue).to(beAKindOf(NSNull.self)) case .notPresent: expect(ipValue).to(beNil()) } } func adjustData(withIdfa idfa: KeyPresence = .defaultValue, adjustId: KeyPresence = .defaultValue, networkID: KeyPresence = .notPresent, idfv: KeyPresence = .defaultValue, ip: KeyPresence = .defaultValue, campaign: KeyPresence = .defaultValue, adGroup: KeyPresence = .defaultValue, creative: KeyPresence = .defaultValue, network: KeyPresence = .defaultValue) -> [String: Any] { var data: [String: Any] = [ "clickLabel": "clickey", "trackerToken": "6abc940", "trackerName": "Instagram Profile::IG Spanish" ] updateMapping(inData: &data, keyPresence: idfa, key: AttributionKey.idfa.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfa) updateMapping(inData: &data, keyPresence: idfv, key: AttributionKey.idfv.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfv) updateMapping(inData: &data, keyPresence: adjustId, key: AttributionKey.Adjust.id.rawValue, defaultValue: AttributionDataMigratorTests.defaultNetworkId) updateMapping(inData: &data, keyPresence: networkID, key: AttributionKey.networkID.rawValue, defaultValue: AttributionDataMigratorTests.defaultRCNetworkId) updateMapping(inData: &data, keyPresence: ip, key: AttributionKey.ip.rawValue, defaultValue: AttributionDataMigratorTests.defaultIp) updateMapping(inData: &data, keyPresence: campaign, key: AttributionKey.Adjust.campaign.rawValue, defaultValue: "IG Spanish") updateMapping(inData: &data, keyPresence: adGroup, key: AttributionKey.Adjust.adGroup.rawValue, defaultValue: "an_ad_group") updateMapping(inData: &data, keyPresence: creative, key: AttributionKey.Adjust.creative.rawValue, defaultValue: "a_creative") updateMapping(inData: &data, keyPresence: network, key: AttributionKey.Adjust.network.rawValue, defaultValue: "Instagram Profile") return data } func appsFlyerData(withIDFA idfa: KeyPresence = .defaultValue, appsFlyerId: KeyPresence = .defaultValue, networkID: KeyPresence = .notPresent, idfv: KeyPresence = .defaultValue, channel: KeyPresence = .defaultValue, mediaSource: KeyPresence = .notPresent, adKey: KeyPresence = .defaultValue, adGroup: KeyPresence = .notPresent, adId: KeyPresence = .defaultValue, campaign: KeyPresence = .defaultValue, adSet: KeyPresence = .defaultValue, adKeywords: KeyPresence = .defaultValue, ip: KeyPresence = .defaultValue) -> [String: Any] { var data: [String: Any] = [ "adset_id": "23847301359550211", "campaign_id": "23847301359200211", "click_time": "2021-05-04 18:08:51.000", "iscache": false, "adgroup_id": "238473013556789090", "is_mobile_data_terms_signed": true, "match_type": "srn", "agency": NSNull(), "retargeting_conversion_type": "none", "install_time": "2021-05-04 18:20:45.050", "af_status": "Non-organic", "http_referrer": NSNull(), "is_paid": true, "is_first_launch": false, "is_fb": true, "af_siteid": NSNull(), "af_message": "organic install" ] updateMapping(inData: &data, keyPresence: idfa, key: AttributionKey.idfa.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfa) updateMapping(inData: &data, keyPresence: idfv, key: AttributionKey.idfv.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfv) updateMapping(inData: &data, keyPresence: appsFlyerId, key: AttributionKey.AppsFlyer.id.rawValue, defaultValue: AttributionDataMigratorTests.defaultNetworkId) updateMapping(inData: &data, keyPresence: networkID, key: AttributionKey.networkID.rawValue, defaultValue: AttributionDataMigratorTests.defaultRCNetworkId) updateMapping(inData: &data, keyPresence: channel, key: AttributionKey.AppsFlyer.channel.rawValue, defaultValue: "Facebook") updateMapping(inData: &data, keyPresence: mediaSource, key: AttributionKey.AppsFlyer.mediaSource.rawValue, defaultValue: "Facebook Ads") updateMapping(inData: &data, keyPresence: adKey, key: AttributionKey.AppsFlyer.ad.rawValue, defaultValue: "ad.mp4") updateMapping(inData: &data, keyPresence: adGroup, key: AttributionKey.AppsFlyer.adGroup.rawValue, defaultValue: "1111 - tm - aaa - US - 999 v1") updateMapping(inData: &data, keyPresence: adId, key: AttributionKey.AppsFlyer.adId.rawValue, defaultValue: "23847301457860211") updateMapping(inData: &data, keyPresence: campaign, key: AttributionKey.AppsFlyer.campaign.rawValue, defaultValue: "0111 - mm - aaa - US - best creo 10 - Copy") updateMapping(inData: &data, keyPresence: adSet, key: AttributionKey.AppsFlyer.adSet.rawValue, defaultValue: "0005 - tm - aaa - US - best 8") updateMapping(inData: &data, keyPresence: adKeywords, key: AttributionKey.AppsFlyer.adKeywords.rawValue, defaultValue: "keywords for ad") updateMapping(inData: &data, keyPresence: ip, key: AttributionKey.ip.rawValue, defaultValue: AttributionDataMigratorTests.defaultIp) return data } func branchData(withIDFA idfa: KeyPresence = .defaultValue, idfv: KeyPresence = .defaultValue, ip: KeyPresence = .defaultValue, channel: KeyPresence = .defaultValue, campaign: KeyPresence = .defaultValue) -> [String: Any] { var data: [String: Any] = [ "+is_first_session": false, "+clicked_branch_link": false ] updateMapping(inData: &data, keyPresence: idfa, key: AttributionKey.idfa.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfa) updateMapping(inData: &data, keyPresence: idfv, key: AttributionKey.idfv.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfv) updateMapping(inData: &data, keyPresence: ip, key: AttributionKey.ip.rawValue, defaultValue: AttributionDataMigratorTests.defaultIp) updateMapping(inData: &data, keyPresence: channel, key: AttributionKey.Branch.channel.rawValue, defaultValue: "Facebook") updateMapping(inData: &data, keyPresence: campaign, key: AttributionKey.Branch.campaign.rawValue, defaultValue: "Facebook Ads 01293") return data } func mParticleData(withIDFA idfa: KeyPresence = .defaultValue, idfv: KeyPresence = .defaultValue, mParticleId: KeyPresence = .defaultValue, networkID: KeyPresence = .notPresent, ip: KeyPresence = .defaultValue) -> [String: Any] { var data: [String: Any] = [:] updateMapping(inData: &data, keyPresence: idfa, key: AttributionKey.idfa.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfa) updateMapping(inData: &data, keyPresence: idfv, key: AttributionKey.idfv.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfv) updateMapping(inData: &data, keyPresence: mParticleId, key: AttributionKey.MParticle.id.rawValue, defaultValue: AttributionDataMigratorTests.defaultNetworkId) updateMapping(inData: &data, keyPresence: networkID, key: AttributionKey.networkID.rawValue, defaultValue: AttributionDataMigratorTests.defaultRCNetworkId) updateMapping(inData: &data, keyPresence: ip, key: AttributionKey.ip.rawValue, defaultValue: AttributionDataMigratorTests.defaultIp) return data } func facebookOrTenjinData( withIDFA idfa: KeyPresence = .defaultValue, idfv: KeyPresence = .defaultValue, ip: KeyPresence = .defaultValue ) -> [String: Any] { var data: [String: Any] = [:] updateMapping(inData: &data, keyPresence: idfa, key: AttributionKey.idfa.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfa) updateMapping(inData: &data, keyPresence: idfv, key: AttributionKey.idfv.rawValue, defaultValue: AttributionDataMigratorTests.defaultIdfv) updateMapping(inData: &data, keyPresence: ip, key: AttributionKey.ip.rawValue, defaultValue: AttributionDataMigratorTests.defaultIp) return data } private func updateMapping( inData: inout [String: Any], keyPresence: KeyPresence, key: String, defaultValue: String ) { switch keyPresence { case .defaultValue: inData[key] = defaultValue case .nsNull: inData[key] = NSNull() case .notPresent: break } } }
mit
dduan/swift
test/SourceKit/CodeComplete/complete_member.swift
14
2911
protocol FooProtocol { /// fooInstanceVar Aaa. /// Bbb. /// /// Ccc. var fooInstanceVar: Int { get } typealias FooTypeAlias1 func fooInstanceFunc0() -> Double func fooInstanceFunc1(a: Int) -> Double subscript(i: Int) -> Double { get } } func test1(a: FooProtocol) { a. } func testOptional1(a: FooProtocol?) { a. } class C { @available(*, unavailable) func unavail() {} } func test_unavail(a: C) { a. } class Base { func foo() {} } class Derived: Base { func foo() {} } func testOverrideUSR() { Derived(). } // RUN: %sourcekitd-test -req=complete -pos=15:5 %s -- %s > %t.response // RUN: diff -u %s.response %t.response // // RUN: %sourcekitd-test -req=complete -pos=19:5 %s -- %s | FileCheck %s -check-prefix=CHECK-OPTIONAL // RUN: %sourcekitd-test -req=complete.open -pos=19:5 %s -- %s | FileCheck %s -check-prefix=CHECK-OPTIONAL-OPEN // CHECK-OPTIONAL: { // CHECK-OPTIONAL: key.kind: source.lang.swift.decl.function.method.instance, // CHECK-OPTIONAL: key.name: "fooInstanceFunc0()", // CHECK-OPTIONAL-LABEL: key.sourcetext: "?.fooInstanceFunc1(<#T##a: Int##Int#>)", // CHECK-OPTIONAL-NEXT: key.description: "fooInstanceFunc1(a: Int)", // CHECK-OPTIONAL-NEXT: key.typename: "Double", // CHECK-OPTIONAL-NEXT: key.context: source.codecompletion.context.thisclass, // CHECK-OPTIONAL-NEXT: key.num_bytes_to_erase: 1, // CHECK-OPTIONAL-NEXT: key.associated_usrs: "s:FP15complete_member11FooProtocol16fooInstanceFunc1FSiSd", // CHECK-OPTIONAL-NEXT: key.modulename: "complete_member" // CHECK-OPTIONAL-NEXT: }, // RUN: %sourcekitd-test -req=complete.open -pos=19:5 %s -- %s | FileCheck %s -check-prefix=CHECK-OPTIONAL-OPEN // CHECK-OPTIONAL-OPEN-NOT: key.description: "fooInstanceFunc1 // CHECK-OPTIONAL-OPEN: key.description: "?.fooInstanceFunc1(a: Int)", // CHECK-OPTIONAL-OPEN-NOT: key.description: "fooInstanceFunc1 // RUN: %sourcekitd-test -req=complete -pos=27:5 %s -- %s | FileCheck %s -check-prefix=CHECK-UNAVAIL // CHECK-UNAVAIL-NOT: key.name: "unavail()", // RUN: %sourcekitd-test -req=complete -pos=39:15 %s -- %s | FileCheck %s -check-prefix=CHECK-OVERRIDE_USR // CHECK-OVERRIDE_USR: { // CHECK-OVERRIDE_USR: key.kind: source.lang.swift.decl.function.method.instance, // CHECK-OVERRIDE_USR-NEXT: key.name: "foo()", // CHECK-OVERRIDE_USR-NEXT: key.sourcetext: "foo()", // CHECK-OVERRIDE_USR-NEXT: key.description: "foo()", // CHECK-OVERRIDE_USR-NEXT: key.typename: "Void", // CHECK-OVERRIDE_USR-NEXT: key.context: source.codecompletion.context.thisclass, // CHECK-OVERRIDE_USR-NEXT: key.num_bytes_to_erase: 0, // CHECK-OVERRIDE_USR-NEXT: key.associated_usrs: "s:FC15complete_member7Derived3fooFT_T_ s:FC15complete_member4Base3fooFT_T_", // CHECK-OVERRIDE_USR-NEXT: key.modulename: "complete_member" // CHECK-OVERRIDE_USR-NEXT: }
apache-2.0
rb-de0/tech.reb-dev.com
Sources/App/Controllers/SubContentRegisterController.swift
2
1218
final class SubContentRegisterController: ResourceRepresentable { private let view: ViewRenderer init(view: ViewRenderer) { self.view = view } func makeResource() -> Resource<Subcontent>{ return Resource( index: index, store: store ) } func index(request: Request) throws -> ResponseRepresentable { return try view.makeWithBase(request: request, path: "subcontent-register") } func store(request: Request) throws -> ResponseRepresentable { do{ let subContent = try Subcontent(request: request) try subContent.save() return Response(redirect: "/subcontents/edit/\(subContent.name)?message=\(SuccessMessage.subContentRegister)") } catch { let context: NodeRepresentable = [ "name": request.data["name"]?.string ?? "", "content": request.data["content"]?.string ?? "", "error_message": error.localizedDescription ] return try view.makeWithBase(request: request, path: "subcontent-register", context: context) } } }
mit
StreamOneNL/iOS-SDK
StreamOneSDK/Request.swift
1
5262
// // Request.swift // StreamOneSDK // // Created by Nicky Gerritsen on 25-07-15. // Copyright © 2015 StreamOne. All rights reserved. // import Foundation import Alamofire /** Execute a request to the StreamOne API This class represents a request to the StreamOne API. To execute a new request, first construct an instance of this class by specifying the command and action to the constructor. The various arguments and options of the request can then be specified and then the request can be actually sent to the StreamOne API server by executing the request. Requests will always be sent asynchronously and a callback will be called upon completion This class only supports version 3 of the StreamOne API. All configuration is done using the Config class. This class inherits from RequestBase, which is a very basic request-class implementing only the basics of setting arguments and parameters, and generic signing of requests. This class adds specific signing for users, applications and sessions, as well as a basic caching mechanism. */ public class Request : RequestBase { /** Initialize a request for a given command and action - Parameter command: The command to use - Parameter action: The action to use - Parameter config: The configuration to use */ public override init(command: String, action: String, config: Config) { super.init(command: command, action: action, config: config) // Check if a default account is specified and set it as a parameter. Can later be overridden if let account = config.defaultAccountId { parameters["account"] = account } // Set correct authentication_type parameter switch config.authenticationType { case .User(id: _, psk: _): parameters["authentication_type"] = "user" case .Application(id: _, psk: _): parameters["authentication_type"] = "application" } } /** Retrieve the parameters used for signing - Returns: A dictionary containing the parameters needed for signing */ override func parametersForSigning() -> [String : String] { var parameters = super.parametersForSigning() switch (config.authenticationType) { case let .User(id: id, psk: _): parameters["user"] = id case let .Application(id: id, psk: _): parameters["application"] = id } return parameters } /** Execute the prepared request If the request can be retrieved from the cache, it will do so. Otherwise, this will sign the request, send it to the API server, and process the response. When done, it will call the provided callback with the response. Note that the callback will be called on the same thread as the caller of this function. - Parameter callback: The callback to call when processing the response is done */ override public func execute(callback: (response: Response) -> Void) { if let response = retrieveFromCache() { callback(response: response) } else { super.execute(callback) } } /** Process the result from a request This will cache the response if possible before calling the callback - Parameter result: The result from a HTTP request - Parameter callback: The callback to call when processing the result is done */ override func processResult(result: Result<AnyObject, NSError>, callback: (response: Response) -> Void) { super.processResult(result) { (response) -> Void in self.saveCache(response) callback(response: response) } } /** Determine the key to use for caching - Returns: the key to use for caching */ internal func cacheKey() -> String { return "s1:request:\(path())?\(parameters.urlEncode())#\(arguments.urlEncode())" } /** Attempt to retrieve the response for this request from the cache - Returns: The cached response if it was found in the cache; nil otherwise */ internal func retrieveFromCache() -> Response? { let cache = config.requestCache let cachedData = cache.getKey(cacheKey()) if let cachedData = cachedData { let result = Result<AnyObject, NSError>.Success(cachedData) var response = Response(result: result) response.fromCache = true response.cacheAge = cache.ageOfKey(cacheKey()) return response } return nil } /** Save the result of the current request to the cache This method only saves to cache if the request is cacheable, and if the request was not retrieved from the cache. */ internal func saveCache(response: Response) { if response.cacheable && !response.fromCache { switch response.result { case let .Success(object): let cache = config.requestCache cache.setKey(cacheKey(), value: object) default: break } } } }
mit
TrustWallet/trust-wallet-ios
TrustTests/Factories/TokenObject.swift
1
611
// Copyright DApps Platform Inc. All rights reserved. import Foundation @testable import Trust import TrustCore extension TokenObject { static func make( contract: Address = EthereumAddress.zero, name: String = "Viktor", coin: Coin = .ethereum, type: TokenObjectType = .coin, symbol: String = "VIK", value: String = "" ) -> TokenObject { return TokenObject( contract: contract.description, name: name, coin: coin, type: type, symbol: symbol, value: value ) } }
gpl-3.0
rogertjr/chatty
Chatty/Chatty/View/ReceiverCell.swift
1
836
// // ReceiverCell.swift // Chatty // // Created by Roger on 01/09/17. // Copyright © 2017 Decodely. All rights reserved. // import UIKit class ReceiverCell: UITableViewCell { @IBOutlet weak var message: UITextView! @IBOutlet weak var messageBackground: UIImageView! func clearCellData() { self.message.text = nil self.message.isHidden = false self.messageBackground.image = nil } override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none self.message.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5) self.messageBackground.layer.cornerRadius = 15 self.messageBackground.clipsToBounds = true } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
jdpepperman/Emma-zing
Symbol.swift
1
1749
// // Symbol.swift // Emma-zing // // Created by Joshua Pepperman on 11/24/14. // Copyright (c) 2014 Joshua Pepperman. All rights reserved. // import SpriteKit enum SymbolType: Int, Printable { case Unknown = 0, MyloXyloto, HurtsLikeHeaven, Paradise, CharlieBrown, UsAgainstTheWorld, MMIX, EveryTeardropIsAWaterfall, MajorMinus, UFO, PrincessOfChina, UpInFlames, AHopefulTransmission, DontLetItBreakYourHeart, UpWithTheBirds var spriteName: String { let spriteNames = [ "MyloXyloto", "HurtsLikeHeaven", "Paradise", "CharlieBrown", "UsAgainstTheWorld", "MMIX", "EveryTeardropIsAWaterfall", "MajorMinus", "UFO", "PrincessOfChina", "UpInFlames", "AHopefullTransmission", "DontLetItBreakYourHeart", "UpWithTheBirds"] return spriteNames[rawValue - 1] } var highlightedSpriteName: String { return spriteName + "-Highlighted" } var description: String { return spriteName } static func random() -> SymbolType { return SymbolType(rawValue: Int(arc4random_uniform(6)) + 1)! } static func random(listToChooseFrom: [Int]) -> SymbolType { var index = Int(arc4random_uniform(UInt32(listToChooseFrom.count))) //5)) + 1 return SymbolType(rawValue: listToChooseFrom[index])! } } class Symbol: Printable, Hashable { var column: Int var row: Int let symbolType: SymbolType var sprite: SKSpriteNode? var description: String { return "type:\(symbolType) square:(\(column),\(row))" } var hashValue: Int { return row*10 + column } init(column: Int, row: Int, symbolType: SymbolType) { self.column = column self.row = row self.symbolType = symbolType } } func ==(lhs: Symbol, rhs: Symbol) -> Bool { return lhs.column == rhs.column && lhs.row == rhs.row }
gpl-2.0
alexs555/PitchPerfect
Pitch Perfect/PlaySoundsViewController.swift
1
1879
// // PlaySoundsViewController.swift // Pitch Perfect // // Created by Алексей Шпирко on 07/06/15. // Copyright (c) 2015 AlexShpirko LLC. All rights reserved. // import UIKit import AVFoundation class PlaySoundsViewController: UIViewController { private enum Effects { case Reverb, Echo, Chipmonk, DartVader, Slow, Quick } private var audioEngine: SoundsEngine! var receivedAudio:RecorderedAudio! override func viewDidLoad() { super.viewDidLoad() //Facade for audio effects audioEngine = SoundsEngine(filePathUrl:receivedAudio.filePathUrl!) } // MARK: - IBActions @IBAction func playSoundSlowly(sender: UIButton) { playEffect(.Slow, value: 0.5) } @IBAction func playSoundFast(sender: UIButton) { playEffect(.Quick, value: 1.5) } @IBAction func chipmonkBtnPressed(sender: UIButton) { playEffect(.Chipmonk, value: 1000) } @IBAction func playDatrVaderEffect(sender: UIButton) { playEffect(.DartVader, value: -1000) } @IBAction func playReverberation(sender: UIButton) { playEffect(.Reverb, value: -50) } @IBAction func playEcho(sender: UIButton) { playEffect(.Echo, value: 40) } @IBAction func stopPlayingAudio(sender: UIButton) { audioEngine.stopPlaying() } // MARK: - Private private func playEffect(effect:Effects, value:Float) { switch effect { case .Reverb: audioEngine.playAudioWithReverb(value) case .Echo: audioEngine.playAudioWithEcho(value) case .Chipmonk,.DartVader: audioEngine.playAudioWithPitch(value) case .Slow,.Quick: audioEngine.playWithRate(value) } } }
mit
snakenet-org/snJSON
snJson/JsonObject.swift
1
8507
// // JsonObject.swift // json-swift // // Created by Marc Fiedler on 08/07/15. // Copyright (c) 2015 snakeNet.org. All rights reserved. // import UIKit /// Errors that can occur in the JSON Object public enum JsonError: ErrorType { case Unknown case SyntaxError case InvalidData case InvalidType case IndexNotFound case NetworkError } /// A JSON Object. Each Object is also an Element in JSON public class JsonObject { public static let version = 3 // MARK: - Public API / Members - /// Type of the element. Is defined in JsonElement.Types public var type: Int! public var string: String? public var int: Int? public var double: Double? public var dict: NSDictionary? public var array: NSArray? /// Element types public struct Types{ // mostly for the value part of a pair or a value // part of an Array or a Dict public static let Unknown: Int = -1 public static let Integer: Int = 1 public static let String: Int = 2 public static let Double: Int = 3 public static let Array: Int = 4 public static let Dictionary: Int = 5 } // MARK: - Privates private var mData = Dictionary<String, JsonObject>() // MARK: - Public API / Methods /// empty initializer public init(){ // every initial object is always a dict. self.type = Types.Dictionary // MARK: - Maybe change this in the future? } public init(data: NSData) throws { do{ try serialize(data) } catch let error as JsonError { // rethrow from here throw error } } public init(str: NSString) throws { // convert the NSString to NSData (for JSONObjectWithData, if that works, serialize the string if let data: NSData = str.dataUsingEncoding(NSUTF8StringEncoding) { do{ try serialize(data) } catch let error as JsonError { // rethrow from here throw error } } else{ // throw an invalid data error if dataUsingEncoding fails throw JsonError.InvalidData } } public init(obj: AnyObject) throws { do{ try parse(obj) } catch let error as JsonError { throw error } } private func serialize(data: NSData) throws { // get the data out of the NSString and serialize it correctly var jsonData: AnyObject? do { jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) } catch { throw JsonError.SyntaxError } // if everything went good, parse the JSON Data do{ try parse(jsonData) } catch let error as JsonError { throw error } } private func parse(val: AnyObject?) throws { self.type = Types.Unknown if let _ = val as? Int { type = Types.Integer self.int = (val as! Int) // while we are at it, convert the int also to a string self.string = String( val as! Int ) } if let _ = val as? Double { type = Types.Double self.double = (val as! Double) // save the same as a string value es well self.string = String( stringInterpolationSegment: val as! Double) } if let _ = val as? String { type = Types.String self.string = (val as! String) } if let vArr: NSArray = val as? NSArray { type = Types.Array var count: Int = 0 for vl in vArr { do{ try set("\(count)", val: vl) } catch let error as JsonError{ throw error } count++ } self.array = vArr } if let vDict = val as? NSDictionary { type = Types.Dictionary for (key, val) in vDict { do{ try set(key as! String, val: val) } catch let error as JsonError{ throw error } } self.dict = vDict } // check if a type was assigned or not if( self.type == Types.Unknown ){ throw JsonError.InvalidType } } private func getJsonArray() -> Array<AnyObject> { var jsonArray = Array<AnyObject>() for( _, val ) in mData { switch( val.type ){ case Types.Array: jsonArray.append( val.getJsonArray() ) case Types.Dictionary: jsonArray.append( val.getJsonDict() ) case Types.Double: jsonArray.append( val.double! ) case Types.String: jsonArray.append( val.string! ) case Types.Integer: jsonArray.append( val.int! ) default: print("Error, default in getJsonArray") } } return jsonArray } private func getJsonDict() -> Dictionary<String, AnyObject>{ var jsonDict = Dictionary<String, AnyObject>() for( key, val ) in mData { switch( val.type ){ case Types.Array: jsonDict[key] = val.getJsonArray() case Types.Dictionary: jsonDict[key] = val.getJsonDict() case Types.String: jsonDict[key] = val.string case Types.Integer: jsonDict[key] = val.int case Types.Double: jsonDict[key] = val.double default: print("Error, default in getJsonDict") } } return jsonDict } public func getJsonString() -> String { var jsonString: String = String() // just define the start point according to the type of this object if( type == Types.Array ){ let jsonArray = getJsonArray() if NSJSONSerialization.isValidJSONObject(jsonArray) { if let data = try? NSJSONSerialization.dataWithJSONObject(jsonArray, options: NSJSONWritingOptions.PrettyPrinted) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { jsonString = string as String } } } } else{ let jsonDict = getJsonDict() if NSJSONSerialization.isValidJSONObject(jsonDict) { if let data = try? NSJSONSerialization.dataWithJSONObject(jsonDict, options: NSJSONWritingOptions.PrettyPrinted) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { jsonString = string as String } } } } return jsonString } public subscript(key: AnyObject) -> AnyObject? { get{ return get(key) } set(val){ do{ try set(key, val: val!) } catch { // MARK :- This might be better to throw as well?? print("Error, could not set value") } } } public subscript(key: AnyObject) -> JsonObject? { return get(key) } public func get(key: AnyObject) -> JsonObject? { let empty: JsonObject? = nil guard let data: JsonObject = mData["\(key)"] else { // return nil if this key does not exist print("JsonObject [get] - Data not found") return empty } return data } public func set(key: AnyObject, val: AnyObject) throws { do{ mData["\(key)"] = try JsonObject(obj: val) } catch let error as JsonError{ throw error } } }
mit
practicalswift/swift
test/TBD/struct.swift
7
8095
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s -enable-resilience // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s -enable-testing // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s -enable-resilience -enable-testing // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s -O // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s -enable-resilience -O // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s -enable-testing -O // RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -validate-tbd-against-ir=all %s -enable-resilience -enable-testing -O // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -typecheck -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/typecheck.tbd // RUN: %target-swift-frontend -emit-ir -parse-as-library -module-name test %s -emit-tbd -emit-tbd-path %t/emit-ir.tbd // RUN: diff -u %t/typecheck.tbd %t/emit-ir.tbd public struct StructPublicNothing {} public struct StructPublicInit { public init() {} public init(public_: Int) {} internal init(internal_: Int) {} private init(private_: Int) {} } public struct StructPublicMethods { public init() {} public func publicMethod() {} internal func internalMethod() {} private func privateMethod() {} } public struct StructPublicProperties { public let publicLet: Int = 0 internal let internalLet: Int = 0 private let privateLet: Int = 0 public var publicVar: Int = 0 internal var internalVar: Int = 0 private var privateVar: Int = 0 public var publicVarGet: Int { return 0 } internal var internalVarGet: Int { return 0 } private var privateVarGet: Int { return 0 } public var publicVarGetSet: Int { get { return 0 } set {} } internal var internalVarGetSet: Int { get { return 0 } set {} } private var privateVarGetSet: Int { get { return 0 } set {} } } public struct StructPublicSubscripts { public subscript(publicGet _: Int) -> Int { return 0 } internal subscript(internalGet _: Int) -> Int { return 0 } private subscript(privateGet _: Int) -> Int { return 0 } public subscript(publicGetSet _: Int) -> Int { get {return 0 } set {} } internal subscript(internalGetSet _: Int) -> Int { get {return 0 } set {} } private subscript(privateGetSet _: Int) -> Int { get {return 0 } set {} } } public struct StructPublicStatics { public static func publicStaticFunc() {} internal static func internalStaticFunc() {} private static func privateStaticFunc() {} public static let publicLet: Int = 0 internal static let internalLet: Int = 0 private static let privateLet: Int = 0 public static var publicVar: Int = 0 internal static var internalVar: Int = 0 private static var privateVar: Int = 0 public static var publicVarGet: Int { return 0 } internal static var internalVarGet: Int { return 0 } private static var privateVarGet: Int { return 0 } public static var publicVarGetSet: Int { get { return 0 } set {} } internal static var internalVarGetSet: Int { get { return 0 } set {} } private static var privateVarGetSet: Int { get { return 0 } set {} } } public struct StructPublicGeneric<T, U, V> { public var publicVar: T internal var internalVar: U private var privateVar: V public var publicVarConcrete: Int = 0 internal var internalVarConcrete: Int = 0 private var privateVarConcrete: Int = 0 public init<S>(t: T, u: U, v: V, _: S) { publicVar = t internalVar = u privateVar = v } public func publicGeneric<A>(_: A) {} internal func internalGeneric<A>(_: A) {} private func privateGeneric<A>(_: A) {} public static func publicStaticGeneric<A>(_: A) {} internal static func internalStaticGeneric<A>(_: A) {} private static func privateStaticGeneric<A>(_: A) {} } internal struct StructInternalNothing {} internal struct StructInternalInit { internal init() {} internal init(internal_: Int) {} private init(private_: Int) {} } internal struct StructInternalMethods { internal init() {} internal func internalMethod() {} private func privateMethod() {} } internal struct StructInternalProperties { internal let internalLet: Int = 0 private let privateLet: Int = 0 internal var internalVar: Int = 0 private var privateVar: Int = 0 internal var internalVarGet: Int { return 0 } private var privateVarGet: Int { return 0 } internal var internalVarGetSet: Int { get { return 0 } set {} } private var privateVarGetSet: Int { get { return 0 } set {} } } internal struct StructInternalSubscripts { internal subscript(internalGet _: Int) -> Int { return 0 } private subscript(privateGet _: Int) -> Int { return 0 } internal subscript(internalGetSet _: Int) -> Int { get {return 0 } set {} } private subscript(privateGetSet _: Int) -> Int { get {return 0 } set {} } } internal struct StructInternalStatics { internal static func internalStaticFunc() {} private static func privateStaticFunc() {} internal static let internalLet: Int = 0 private static let privateLet: Int = 0 internal static var internalVar: Int = 0 private static var privateVar: Int = 0 internal static var internalVarGet: Int { return 0 } private static var privateVarGet: Int { return 0 } internal static var internalVarGetSet: Int { get { return 0 } set {} } private static var privateVarGetSet: Int { get { return 0 } set {} } } internal struct StructInternalGeneric<T, U, V> { internal var internalVar: U private var privateVar: V internal var internalVarConcrete: Int = 0 private var privateVarConcrete: Int = 0 internal init<S>(t: T, u: U, v: V, _: S) { internalVar = u privateVar = v } internal func internalGeneric<A>(_: A) {} private func privateGeneric<A>(_: A) {} internal static func internalStaticGeneric<A>(_: A) {} private static func privateStaticGeneric<A>(_: A) {} } private struct StructPrivateNothing {} private struct StructPrivateInit { private init() {} private init(private_: Int) {} } private struct StructPrivateMethods { private init() {} private func privateMethod() {} } private struct StructPrivateProperties { private let privateLet: Int = 0 private var privateVar: Int = 0 private var privateVarGet: Int { return 0 } private var privateVarGetSet: Int { get { return 0 } set {} } } private struct StructPrivateSubscripts { private subscript(privateGet _: Int) -> Int { return 0 } private subscript(privateGetSet _: Int) -> Int { get {return 0 } set {} } } private struct StructPrivateStatics { private static func privateStaticFunc() {} private static let privateLet: Int = 0 private static var privateVar: Int = 0 private static var privateVarGet: Int { return 0 } private static var privateVarGetSet: Int { get { return 0 } set {} } } private struct StructPrivateGeneric<T, U, V> { private var privateVar: V private var privateVarConcrete: Int = 0 private init<S>(t: T, u: U, v: V, _: S) { privateVar = v } private func privateGeneric<A>(_: A) {} private static func privateStaticGeneric<A>(_: A) {} }
apache-2.0
iosClassForBeginner/photoFrame-en
photoFrame-en/ViewController.swift
1
1976
// // ViewController.swift // photoFrame-en // // Created by Wataru Maeda on 2016/12/16. // Copyright © 2016 Wataru Maeda. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var myScroll: UIScrollView! override func viewDidLoad() { super.viewDidLoad() // Specify x-axis, y-axis, width, height of the photo frame var x = 0 as CGFloat let y = 0 as CGFloat let w = myScroll.frame.size.width let h = myScroll.frame.size.height // 1st photo let myImageView1 = UIImageView() myImageView1.frame = CGRect(x: x, y: y, width: w, height: h) myImageView1.image = UIImage(named: "your-photo-1.jpg") myImageView1.contentMode = .scaleAspectFill myImageView1.clipsToBounds = true myScroll.addSubview(myImageView1) // 2nd photo x += w let myImageView2 = UIImageView() myImageView2.frame = CGRect(x: x, y: y, width: w, height: h) myImageView2.image = UIImage(named: "your-photo-2.jpg") myImageView2.contentMode = .scaleAspectFill myImageView2.clipsToBounds = true myScroll!.addSubview(myImageView2) // 3rd photo x += w let myImageView3 = UIImageView() myImageView3.frame = CGRect(x: x, y: y, width: w, height: h) myImageView3.image = UIImage(named: "your-photo-3.jpg") myImageView3.contentMode = .scaleAspectFill myImageView3.clipsToBounds = true myScroll.addSubview(myImageView3) // Specify scroll bounds (3 times wider than original width due to usage of 3 photos) myScroll.contentSize.width = w * 3 // Paging enabled myScroll.isPagingEnabled = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Client/Model/Network/WithdrawLocksResponse.swift
1
394
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation struct WithdrawalLocksResponse: Decodable { struct Lock: Decodable { let expiresAt: String let amount: Amount } struct Amount: Decodable { let amount: String let currency: String } let locks: [Lock] let totalLocked: Amount let available: Amount }
lgpl-3.0
toshiapp/toshi-ios-client
Toshi/Controllers/Dapps/Views/DappsTableHeaderView.swift
1
11515
// Copyright (c) 2018 Token Browser, Inc // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import UIKit import QuartzCore protocol DappsSearchHeaderViewDelegate: class { func didRequireCollapsedState(_ headerView: DappsTableHeaderView) func didRequireDefaultState(_ headerView: DappsTableHeaderView) func dappsSearchDidUpdateSearchText(_ headerView: DappsTableHeaderView, searchText: String) } final class DappsTableHeaderView: UIView { let collapsedStateScrollPercentage: CGFloat = 1 let expandedStateScrollPercentage: CGFloat = 0 private var screenWidth = UIScreen.main.bounds.width private(set) lazy var sizeRange: ClosedRange<CGFloat> = -280 ... (-59 - UIApplication.shared.statusBarFrame.height) private weak var delegate: DappsSearchHeaderViewDelegate? private lazy var minTextFieldWidth: CGFloat = screenWidth - (2 * 40) private lazy var maxTextFieldWidth: CGFloat = screenWidth - (2 * 15) private var heightConstraint: NSLayoutConstraint? private var searchStackBottomConstraint: NSLayoutConstraint? private var searchStackLeftConstraint: NSLayoutConstraint? private var searchStackRightConstraint: NSLayoutConstraint? private var searchStackHeightConstraint: NSLayoutConstraint? private var shouldShowCancelButton = false private lazy var expandedBackgroundView: UIView = { let backgroundView = UIView() backgroundView.backgroundColor = Theme.tintColor backgroundView.isUserInteractionEnabled = false backgroundView.clipsToBounds = true return backgroundView }() private lazy var bubblesImageView: UIImageView = { let bubblesImageView = UIImageView(image: ImageAsset.bubbles) return bubblesImageView }() private lazy var collapsedBackgroundView: UIView = { let backgroundView = UIView() backgroundView.backgroundColor = .white backgroundView.isUserInteractionEnabled = false backgroundView.alpha = 0.0 return backgroundView }() private lazy var titleLabel: UILabel = { let label = UILabel() label.textColor = Theme.viewBackgroundColor label.text = Localized.dapps_search_header_title label.font = Theme.semibold(size: 20) label.textAlignment = .center return label }() private lazy var iconImageView: UIImageView = { let imageView = UIImageView() imageView.size(CGSize(width: 48, height: 48)) imageView.contentMode = .scaleAspectFit imageView.image = ImageAsset.logo return imageView }() private(set) lazy var searchTextField: InsetTextField = { let textField = InsetTextField(xInset: 20, yInset: 0) textField.delegate = self textField.autocapitalizationType = .none textField.autocorrectionType = .no textField.attributedPlaceholder = NSAttributedString(string: Localized.dapps_search_placeholder, attributes: [.foregroundColor: Theme.greyTextColor]) textField.borderStyle = .none textField.layer.cornerRadius = 5 return textField }() private lazy var searchTextFieldBackgroundView: UIView = { let backgroundView = UIView() backgroundView.backgroundColor = Theme.searchBarColor backgroundView.alpha = 0.0 backgroundView.isUserInteractionEnabled = false backgroundView.layer.cornerRadius = 5 return backgroundView }() private lazy var cancelButton: UIButton = { let cancelButton = UIButton() cancelButton.setTitle(Localized.cancel_action_title, for: .normal) cancelButton.setTitleColor(Theme.tintColor, for: .normal) cancelButton.addTarget(self, action: #selector(didTapCancelButton), for: .touchUpInside) cancelButton.setContentCompressionResistancePriority(.required, for: .horizontal) return cancelButton }() private lazy var searchFieldStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.alignment = .center stackView.spacing = 6 // prevents jump when typing begins stackView.addSubview(searchTextFieldBackgroundView) stackView.addArrangedSubview(searchTextField) searchTextField.topToSuperview() searchTextField.bottomToSuperview() searchTextFieldBackgroundView.edges(to: searchTextField) stackView.addArrangedSubview(cancelButton) cancelButton.topToSuperview() cancelButton.bottomToSuperview() cancelButton.isHidden = true return stackView }() // MARK: - Initialization /// Designated initializer /// /// - Parameters: /// - frame: The frame to pass through to super. /// - delegate: The delegate to notify of changes. init(frame: CGRect, delegate: DappsSearchHeaderViewDelegate) { self.delegate = delegate super.init(frame: frame) backgroundColor = .clear addSubviewsAndConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Setup private func addSubviewsAndConstraints() { heightConstraint = height(280) addSubview(expandedBackgroundView) expandedBackgroundView.edges(to: self) expandedBackgroundView.addSubview(bubblesImageView) bubblesImageView.bottom(to: expandedBackgroundView) bubblesImageView.centerX(to: expandedBackgroundView) addSubview(collapsedBackgroundView) collapsedBackgroundView.edges(to: self) let separatorView = BorderView() collapsedBackgroundView.addSubview(separatorView) separatorView.addHeightConstraint() separatorView.edgesToSuperview(excluding: .top) addSubview(searchFieldStackView) addSubview(iconImageView) addSubview(titleLabel) iconImageView.size(CGSize(width: 48, height: 48)) iconImageView.centerX(to: self) iconImageView.bottomToTop(of: titleLabel, offset: -(.mediumInterItemSpacing)) titleLabel.left(to: self, offset: .mediumInterItemSpacing) titleLabel.right(to: self, offset: -(.mediumInterItemSpacing)) titleLabel.bottomToTop(of: searchFieldStackView, offset: -(CGFloat.giantInterItemSpacing)) searchStackLeftConstraint = searchFieldStackView.left(to: self, offset: 40) searchStackRightConstraint = searchFieldStackView.right(to: self, offset: -40) searchStackHeightConstraint = searchFieldStackView.height(56) searchStackBottomConstraint = searchFieldStackView.bottom(to: self, offset: -(.giantInterItemSpacing)) } func adjustNonAnimatedProperties(to percentage: CGFloat) { let diff = (sizeRange.lowerBound - sizeRange.upperBound) * -1 let height = (sizeRange.lowerBound + (percentage * diff)) * -1 heightConstraint?.constant = height searchStackHeightConstraint?.constant = resize(1 - percentage, in: 36 ... 56) searchStackLeftConstraint?.constant = resize(1 - percentage, in: 15 ... 40) searchStackRightConstraint?.constant = resize(percentage, in: -40 ... -15) searchStackBottomConstraint?.constant = percentage.map(from: 0 ... 1, to: -40 ... -15) if percentage >= 1 && shouldShowCancelButton { cancelButton.isHidden = false shouldShowCancelButton = false } } func adjustAnimatedProperties(to percentage: CGFloat) { expandedBackgroundView.alpha = fadeOut(percentage, in: 0.77 ... 1) collapsedBackgroundView.alpha = fadeIn(percentage, in: 0.77 ... 1) iconImageView.alpha = fadeOut(percentage, in: 0.0 ... 0.46) titleLabel.alpha = fadeOut(percentage, in: 0.0 ... 0.46) let shadowOpacity = Float((1 - percentage).map(from: 0 ... 1, to: 0 ... 0.3)) searchTextField.addShadow(xOffset: 1, yOffset: 1, radius: 3, opacity: shadowOpacity) searchTextField.backgroundColor = UIColor.white.withAlphaComponent(fadeOut(percentage, in: 0.89 ... 1)) searchTextFieldBackgroundView.alpha = fadeIn(percentage, in: 0.89 ... 1) searchTextField.xInset = (1 - percentage).map(from: 0 ... 1, to: 14 ... 19) } func didScroll(to percentage: CGFloat) { adjustAnimatedProperties(to: percentage) adjustNonAnimatedProperties(to: percentage) } func cancelSearch() { hideCancelButton() searchTextField.resignFirstResponder() searchTextField.text = nil delegate?.didRequireDefaultState(self) } func showCancelButton() { layoutIfNeeded() cancelButton.isHidden = false UIView.animate(withDuration: 0.2) { self.layoutIfNeeded() } shouldShowCancelButton = false } private func hideCancelButton() { layoutIfNeeded() cancelButton.isHidden = true UIView.animate(withDuration: 0.2) { self.layoutIfNeeded() } } private func resize(_ percentage: CGFloat, in range: ClosedRange<CGFloat>) -> CGFloat { return percentage.map(from: 0 ... 1, to: range).clamp(to: range) } private func fadeIn(_ percentage: CGFloat, in range: ClosedRange<CGFloat>) -> CGFloat { return percentage.clamp(to: range).map(from: range, to: 0 ... 1) } private func fadeOut(_ percentage: CGFloat, in range: ClosedRange<CGFloat>) -> CGFloat { return 1 - percentage.clamp(to: range).map(from: range, to: 0 ... 1) } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { // Point inside is overriden to enable swiping on the header if searchFieldStackView.frame.contains(point) { return true } else { return false } } @objc private func didTapCancelButton() { hideCancelButton() searchTextField.resignFirstResponder() searchTextField.text = nil delegate?.didRequireDefaultState(self) } } extension DappsTableHeaderView: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { delegate?.didRequireCollapsedState(self) if frame.height > -sizeRange.upperBound { shouldShowCancelButton = true } else { showCancelButton() } return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) delegate?.dappsSearchDidUpdateSearchText(self, searchText: updatedText) } return true } }
gpl-3.0
loganisitt/SLPagingViewSwift
Demos/TwitterLike/TwitterLike/AppDelegate.swift
1
6268
// // AppDelegate.swift // TwitterLike // // Created by Stefan Lage on 10/01/15. // Copyright (c) 2015 Stefan Lage. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UITableViewDelegate, UITableViewDataSource { var window: UIWindow? var nav: UINavigationController? var controller: SLPagingViewSwift? var dataSource: NSMutableArray? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.dataSource = NSMutableArray(array: ["Hello world!", "Shaqtin' a fool!", "YEAHHH!", "Hello world!", "Shaqtin' a fool!", "YEAHHH!", "Hello world!", "Shaqtin' a fool!", "YEAHHH!", "Hello world!", "Shaqtin' a fool!", "YEAHHH!", "Hello world!", "Shaqtin' a fool!", "YEAHHH!"]) var navTitleLabel1 = UILabel() navTitleLabel1.text = "Home" navTitleLabel1.font = UIFont(name: "Helvetica", size: 20) navTitleLabel1.textColor = UIColor.whiteColor() var navTitleLabel2 = UILabel() navTitleLabel2.text = "Discover" navTitleLabel2.font = UIFont(name: "Helvetica", size: 20) navTitleLabel2.textColor = UIColor.whiteColor() var navTitleLabel3 = UILabel() navTitleLabel3.text = "Activity" navTitleLabel3.font = UIFont(name: "Helvetica", size: 20) navTitleLabel3.textColor = UIColor.whiteColor() controller = SLPagingViewSwift(items: [navTitleLabel1, navTitleLabel2, navTitleLabel3], views: [self.tableView(), self.tableView(), self.tableView()], showPageControl: true, navBarBackground: UIColor(red: 0.33, green: 0.68, blue: 0.91, alpha: 1.0)) controller?.currentPageControlColor = UIColor.whiteColor() controller?.tintPageControlColor = UIColor(white: 0.799, alpha: 1.0) controller?.pagingViewMovingRedefine = ({ scrollView, subviews in var i = 0 var xOffset = scrollView.contentOffset.x for v in subviews { var lbl = v as! UILabel var alpha = CGFloat(0) if(lbl.frame.origin.x > 45 && lbl.frame.origin.x < 145) { alpha = 1.0 - (xOffset - (CGFloat(i)*320.0)) / 320.0 } else if (lbl.frame.origin.x > 145 && lbl.frame.origin.x < 245) { alpha = (xOffset - (CGFloat(i)*320.0)) / 320.0 + 1.0 } else if(lbl.frame.origin.x == 145){ alpha = 1.0 } lbl.alpha = CGFloat(alpha) i++ } }) controller?.didChangedPage = ({ currentIndex in println(currentIndex) }) self.nav = UINavigationController(rootViewController: self.controller!) self.window?.rootViewController = self.nav self.window?.backgroundColor = UIColor.whiteColor() self.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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func tableView() -> UITableView { var frame = CGRectMake(0, 0, 320, 568) frame.size.height -= 44 var tableView = UITableView(frame: frame, style: .Plain) tableView.delegate = self tableView.dataSource = self tableView.scrollsToTop = false return tableView } // MARK: - UITableView DataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource!.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 120.0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cellIdentifier = "cellIdentifier" var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier) cell?.textLabel?.numberOfLines = 0 } cell!.imageView?.image = UIImage(named: NSString(format: "avatar_%d.jpg", indexPath.row % 3) as String) cell!.textLabel!.text = self.dataSource?.objectAtIndex(indexPath.row) as? String return cell! } }
mit
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/API/AwesomeCore+Events.swift
1
1991
// // AwesomeCore+Events.swift // Pods // // Created by Evandro Harrison Hoffmann on 6/18/18. // import Foundation public enum EventCode: String { case mvu } public extension AwesomeCore { public static func fetchAttendees(eventSlug: EventCode = .mvu, isFirstPage: Bool = true, params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping ([Attendee], ErrorData?) -> Void) { AttendeeBO.fetchAttendees(eventSlug: eventSlug, isFirstPage: isFirstPage, params: params, response: response) } public static func fetchFilteredAttendeesByTag(eventSlug: EventCode = .mvu, params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping ([Attendee], ErrorData?) -> Void) { AttendeeBO.fetchFilteredAttendeesByTag(eventSlug: eventSlug, params: params, response: response) } public static func fetchEventPurchaseStatus(eventSlug: EventCode = .mvu, params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping (Bool?, ErrorData?) -> Void) { EventPurchaseStatusBO.fetchPurchaseStatus(eventSlug: eventSlug, params: params, response: response) } public static func patchTravelDates(eventSlug: EventCode = .mvu, arrivalDate: String, departureDate: String, forcingUpdate: Bool = false, response: @escaping (Bool, ErrorData?) -> Void) { EventRegistrationBO.patchTravelDates(eventSlug: eventSlug, arrivalDate: arrivalDate, departureDate: departureDate, forcingUpdate: forcingUpdate, response: response) } public static func fetchHomeUserProfile(forcingUpdate: Bool, response: @escaping (HomeUserProfile?, ErrorData?)-> Void) { UserProfileBO.fetchHomeUserProfile(forcingUpdate: forcingUpdate, response: response) } public static func fetchPurchaseStatus(eventSlug: EventCode = .mvu, response: @escaping (PurchaseStatus?, ErrorData?)-> Void) { PurchaseStatusBO.fetchPurchaseStatus(eventSlug: eventSlug, params: .standard, response: response) } }
mit
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Main/View/STTabBar.swift
1
3626
// // STTarBar.swift // XMLYDemo // // Created by xiudou on 2016/12/21. // Copyright © 2016年 CoderST. All rights reserved. // import UIKit /// 定义协议 protocol STTabbarDelegate : class{ func didSelectButtonAtIndex(_ stTabbar : STTabBar, index : Int) } class STTabBar: UIView { // MARK:- 变量 weak var delegate : STTabbarDelegate? fileprivate var selectedButton : STButton? // MARK:- 懒加载 fileprivate lazy var playButton : UIButton = { let playButton = UIButton(type: .custom) playButton.setBackgroundImage(UIImage(named: "tabbar_np_play"), for: UIControlState()) playButton.setBackgroundImage(UIImage(named: "tabbar_np_play"), for: .highlighted) if let currentBackgroundImage = playButton.currentBackgroundImage { playButton.bounds = CGRect(x: 0, y: 0, width: currentBackgroundImage.size.width, height: currentBackgroundImage.size.height); playButton.bounds = CGRect(x: 0, y: 0, width: currentBackgroundImage.size.width, height: currentBackgroundImage.size.height) } playButton.addTarget(self, action: #selector(STTabBar.playButtonAction(_:)), for: .touchDown) return playButton }() fileprivate lazy var itemButtonArray : [STButton] = [STButton]() // 生命周期 override init(frame: CGRect) { super.init(frame: frame) if (!iOS7) { if let backImage = UIImage(named: "tabbar_background"){ backgroundColor = UIColor(patternImage: backImage) } } backgroundColor = UIColor(patternImage: UIImage(named: "tabbar_bg")!) addSubview(playButton) } // 布局子空间 override func layoutSubviews() { super.layoutSubviews() let width = frame.size.width let height = frame.size.height playButton.center = CGPoint(x: width * 0.5, y: height * 0.5) let buttonWidth = width / CGFloat(subviews.count) let buttonHeight = height let buttonY : CGFloat = 0 for (index,button) in itemButtonArray.enumerated(){ button.tag = index var buttonX = CGFloat(index) * buttonWidth if index > 1 { buttonX = buttonX + buttonWidth } button.frame = CGRect(x: buttonX, y: buttonY, width: buttonWidth, height: buttonHeight) } } func creatTabbarItem(_ item : UITabBarItem) { setupUI(item) } @objc fileprivate func playButtonAction(_ button : UIButton){ print("playButtonAction") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension STTabBar { fileprivate func setupUI(_ item : UITabBarItem) { guard let tabbarButton = STButton.creatButton(item) else { return } tabbarButton.addTarget(self, action: #selector(STTabBar.tabbarButtonAction(_:)), for: .touchDown) addSubview(tabbarButton) itemButtonArray.append(tabbarButton) if (itemButtonArray.count == 1) { selectedButton = tabbarButton tabbarButtonAction(tabbarButton) } } @objc fileprivate func tabbarButtonAction(_ button : STButton){ delegate?.didSelectButtonAtIndex(self, index: button.tag) selectedButton!.isSelected = false; button.isSelected = true; selectedButton = button; } }
mit
tomboates/BrilliantSDK
Pod/Classes/Survey.swift
1
3666
// // Survey.swift // Pods // // Created by Phillip Connaughton on 12/5/15. // // import Foundation class Survey: NSObject { var surveyId: UUID! var dismissAction: String? var userAccountCreation: Date? var triggerTimestamp : Date? var event: String? var comment: String? var customerUserId: String? var userType: String? var completedTimestamp: Date? var npsRating: Int? static let triggerTimestampKey = "trigger_timestamp" static let dismissActionKey = "dismiss_action" static let completedTimestampKey = "completed_timestamp" static let npsRatingKey = "nps_rating" static let commentsKey = "comments" static let userAccountCreationKey = "user_account_creation" static let eventKey = "event" static let customerUserIdKey = "user_id" static let userTypeKey = "user_type" static let surveyIdKey = "survey_id" init(surveyId: UUID){ self.surveyId = surveyId } init(map:[String: AnyObject]) { self.triggerTimestamp = map[Survey.triggerTimestampKey] as? Date self.dismissAction = map[Survey.dismissActionKey] as? String self.completedTimestamp = map[Survey.completedTimestampKey] as? Date self.npsRating = map[Survey.npsRatingKey] as? Int self.comment = map[Survey.commentsKey] as? String self.userAccountCreation = map[Survey.userAccountCreationKey] as? Date self.event = map[Survey.eventKey] as? String self.customerUserId = map[Survey.customerUserIdKey] as? String self.userType = map[Survey.userTypeKey] as? String self.surveyId = UUID(uuidString: map[Survey.surveyIdKey] as! String) } func serialize() -> [String: AnyObject] { var map = [String: AnyObject]() map[Survey.triggerTimestampKey] = self.triggerTimestamp as AnyObject? map[Survey.dismissActionKey] = self.dismissAction as AnyObject? map[Survey.completedTimestampKey] = self.completedTimestamp as AnyObject? map[Survey.npsRatingKey] = self.npsRating as AnyObject? map[Survey.commentsKey] = self.comment as AnyObject? map[Survey.userAccountCreationKey] = self.userAccountCreation as AnyObject? map[Survey.eventKey] = self.event as AnyObject? map[Survey.customerUserIdKey] = self.customerUserId as AnyObject? map[Survey.userTypeKey] = self.userType as AnyObject? map[Survey.surveyIdKey] = self.surveyId.uuidString as AnyObject? return map } func serializeForSurvey() -> [String: String] { var map = [String: String]() if(self.triggerTimestamp != nil) { map[Survey.triggerTimestampKey] = String(self.triggerTimestamp!.timeIntervalSince1970) } map[Survey.dismissActionKey] = self.dismissAction if(self.completedTimestamp != nil) { map[Survey.completedTimestampKey] = String(self.completedTimestamp!.timeIntervalSince1970) } if(self.npsRating != nil) { map[Survey.npsRatingKey] = String(self.npsRating!) } map[Survey.commentsKey] = self.comment if(self.userAccountCreation == nil) { map[Survey.userAccountCreationKey] = String(self.userAccountCreation!.timeIntervalSince1970) } map[Survey.eventKey] = self.event map[Survey.customerUserIdKey] = self.customerUserId map[Survey.userTypeKey] = self.userType map[Survey.surveyIdKey] = self.surveyId.uuidString return map } }
mit
kallahir/AlbumTrackr-iOS
AlbumTracker/Release.swift
1
1880
// // Release.swift // AlbumTracker // // Created by Itallo Rossi Lucas on 5/15/16. // Copyright © 2016 AlbumTrackr. All rights reserved. // import CoreData class Release: NSManagedObject { @NSManaged var releaseGroupId: NSNumber @NSManaged var releaseGroupGid: String? @NSManaged var releaseDate: NSDate @NSManaged var name: String? @NSManaged var imagePath: String? @NSManaged var primaryType: String? @NSManaged var secondaryType: String? @NSManaged var isAlbum: Bool struct Keys { static let releaseGroupId = "releaseGroupId" static let releaseGroupGid = "releaseGroupGid" static let releaseDate = "releaseDate" static let name = "name" static let imagePath = "imagePath" static let primaryType = "primaryType" static let secondaryType = "secondaryType" static let isAlbum = "isAlbum" } override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("Release", inManagedObjectContext: context)! super.init(entity: entity,insertIntoManagedObjectContext: context) releaseGroupId = dictionary[Keys.releaseGroupId] as! NSNumber releaseGroupGid = dictionary[Keys.releaseGroupGid] as? String releaseDate = dictionary[Keys.releaseDate] as! NSDate name = dictionary[Keys.name] as? String imagePath = dictionary[Keys.imagePath] as? String primaryType = dictionary[Keys.primaryType] as? String secondaryType = dictionary[Keys.secondaryType] as? String isAlbum = dictionary[Keys.isAlbum] as! Bool } }
agpl-3.0
otakisan/SmartToDo
SmartToDo/Views/TaskListTableViewController.swift
1
13017
// // TaskListTableViewController.swift // SmartToDo // // Created by takashi on 2014/09/15. // Copyright (c) 2014年 ti. All rights reserved. // import UIKit import GoogleMobileAds class TaskListTableViewController: UITableViewController { var taskStoreService : TaskStoreService = TaskStoreService() var tasks : [ToDoTaskEntity] = [] var dayOfTask = NSDate() lazy var prepareForSegueFuncTable : [String:(UIStoryboardSegue,AnyObject!)->Void] = self.initPrepareForSegueFuncTable() var isShowAd = false var interstitial : GADInterstitial? private func initPrepareForSegueFuncTable() -> [String:(UIStoryboardSegue,AnyObject!)->Void] { let funcTable : [String:(UIStoryboardSegue,AnyObject!)->Void] = [ "showToDoEditorV1Segue" : self.prepareForShowToDoEditorV1Segue, "showToUnfinishedTaskListSegue" : self.prepareForShowToUnfinishedTaskListSegue ] return funcTable } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false self.loadAd() // タイトル self.setTitle() // ナビゲーションバーボタンを構成 self.configureRightBarButtonItem() self.configureLeftBarButtonItem() self.tableView.registerNib(UINib(nibName: "TaskListTableViewCell", bundle: nil), forCellReuseIdentifier: "taskListTableViewCell") // self.taskStoreService.clearAllTasks() // テスト上、初期化したい場合はコールする // 本リストに列挙するタスクを取得 self.tasks = self.taskStoreService.getTasks(self.dayOfTask) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let prevTaskCount = self.tasks.count self.reloadTaskList() // タスク数に変更があった場合にのみ広告を表示 if prevTaskCount != self.tasks.count { self.showAd() } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.tasks.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("taskListTableViewCell", forIndexPath: indexPath) as! TaskListTableViewCell // Configure the cell... let task = self.tasks[indexPath.row] cell.taskTitleLabel.text = task.title cell.taskProgressView.progress = Float(task.progress) cell.taskId = task.id return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // self.performSegueWithIdentifier("showToDoEditorSegue", sender: self) self.performSegueWithIdentifier("showToDoEditorV1Segue", sender: self) } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let deleteLog = deleteTask(indexPath) self.showMessageDialog(NSLocalizedString("didDelete", comment: ""), message: String(format: NSLocalizedString("didDeleteMessage", comment: ""), deleteLog.id, deleteLog.title)) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } private func deleteTask(indexPath : NSIndexPath) -> (id : String, title: String) { // 先に行数の元となる配列から要素を削除し、numberOfRowsInSectionで削除後の行数を返却するようにする // 先に削除しないと、deleteRowsAtIndexPathsでエラーになる let rowIndexDeleting = indexPath.row let taskIdDeleting = tasks[rowIndexDeleting].id let taskTitleDeleting = tasks[rowIndexDeleting].title let taskEntityDeleting = tasks.removeAtIndex(rowIndexDeleting) // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) // 念のため、前の処理が全部成功してから実際に削除する self.taskStoreService.deleteEntity(taskEntityDeleting) return (taskIdDeleting, taskTitleDeleting) } private func showMessageDialog(title : String, message : String) { ViewUtility.showMessageDialog(self, title: title, message: message) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { self.prepareForSegueFuncTable[segue.identifier!]!(segue, sender) } private func prepareForShowToDoEditorV1Segue(segue: UIStoryboardSegue, sender: AnyObject!){ // セルをタップした場合は、そのセルからIDを取得し、taskIdにセット // 新規追加:タスクIDは空。締切日の初期値を渡す var vc = segue.destinationViewController as! ToDoEditorV1ViewController if let selectedIndex = self.tableView.indexPathForSelectedRow?.row { var indexPath = NSIndexPath(forRow: selectedIndex, inSection: 0) vc.taskId = (self.tableView.cellForRowAtIndexPath(indexPath) as! TaskListTableViewCell).taskId }else{ vc.initialValues = ["dueDate":self.dayOfTask] } // 遷移先のレフトボタンを構成する(自分に制御を移すため) if var nvc = self.navigationController { var bckItem = UIBarButtonItem(title: NSLocalizedString("BackToList", comment: ""), style: UIBarButtonItemStyle.Bordered, target: self, action: "didBack:") vc.navigationItem.leftBarButtonItem = bckItem } // 戻ってきた時に広告を表示する self.isShowAd = true } private func prepareForShowToUnfinishedTaskListSegue(segue: UIStoryboardSegue, sender: AnyObject!){ // 遷移先のレフトボタンを構成する(自分に制御を移すため) var vc = segue.destinationViewController as! UnfinishedTaskListTableViewController vc.dueDateOfCopy = self.dayOfTask if var nvc = self.navigationController { var bckItem = UIBarButtonItem(title: NSLocalizedString("BackToList", comment: ""), style: UIBarButtonItemStyle.Bordered, target: self, action: "didBack:") vc.navigationItem.leftBarButtonItem = bckItem } } @IBAction private func didBack(sender : AnyObject){ self.navigationController?.popViewControllerAnimated(true) // 保存しなかった変更は消す self.taskStoreService.rollback() } func reloadTaskList(){ self.tasks = self.taskStoreService.getTasks(self.dayOfTask) self.tableView.reloadData() } /** ナビゲーションバーの右ボタンを構成します */ private func configureRightBarButtonItem(){ let datePartOfNow = DateUtility.firstEdgeOfDay(NSDate()) if datePartOfNow.compare(self.dayOfTask) == NSComparisonResult.OrderedAscending || datePartOfNow.compare(self.dayOfTask) == NSComparisonResult.OrderedSame { self.appendCopyButtonIntoNavigationBar() self.appendAddButtonIntoNavigationBar() } } private func appendAddButtonIntoNavigationBar() { let addBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "touchUpInsideAddButton:") self.appendRightBarButtonItem(addBarButtonItem) } private func appendCopyButtonIntoNavigationBar() { let barButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: "touchUpInsideCopyButton:") self.appendRightBarButtonItem(barButton) } private func appendEditButtonIntoNavigationBar() { var inoutparam : [UIBarButtonItem]? = self.navigationItem.leftBarButtonItems self.appendBarButtonItem(&inoutparam, barButtonItem: self.editButtonItem()) } private func appendRightBarButtonItem(barButtonItem : UIBarButtonItem) { if self.navigationItem.rightBarButtonItems != nil { self.navigationItem.rightBarButtonItems!.append(barButtonItem) } else{ self.navigationItem.rightBarButtonItems = [barButtonItem] } } private func todayOrFuture() -> Bool { let datePartOfNow = DateUtility.firstEdgeOfDay(NSDate()) return datePartOfNow.compare(self.dayOfTask) == NSComparisonResult.OrderedAscending || datePartOfNow.compare(self.dayOfTask) == NSComparisonResult.OrderedSame } private func configureLeftBarButtonItem(){ if self.todayOrFuture() { self.appendEditButtonIntoNavigationBar() } } private func appendBarButtonItem(inout barButtonItems : [UIBarButtonItem]?, barButtonItem : UIBarButtonItem){ if barButtonItems != nil { barButtonItems!.append(barButtonItem) } else{ barButtonItems = [barButtonItem] } } private func setTitle() { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy/MM/dd" self.navigationItem.title = dateFormatter.stringFromDate(self.dayOfTask) } @IBAction func touchUpInsideAddButton(sender : AnyObject){ print("add called.", terminator: "") self.performSegueWithIdentifier("showToDoEditorV1Segue", sender: self) } @IBAction func touchUpInsideCopyButton(sender : AnyObject){ self.performSegueWithIdentifier("showToUnfinishedTaskListSegue", sender: self) } private func loadAd() { self.interstitial = GADInterstitial(adUnitID: "ca-app-pub-3119454746977531/6858726401") let gadRequest = GADRequest() self.interstitial?.loadRequest(gadRequest) self.interstitial?.delegate = self } private func showAd() { if self.isShowAd && self.interstitial!.isReady { self.interstitial?.presentFromRootViewController(self) } } } extension TaskListTableViewController : GADInterstitialDelegate { func interstitialDidDismissScreen(ad: GADInterstitial!){ self.loadAd() } func interstitialWillPresentScreen(ad: GADInterstitial!) { self.isShowAd = false } func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!){ print(error) } }
mit
johntvolk/TableViewConfigurator
Example/Tests/Cells/ConfigurableCell.swift
1
641
// // ConfigurableCell.swift // TableViewConfigurator // // Created by John Volk on 3/3/16. // Copyright © 2016 John Volk. All rights reserved. // import UIKit import TableViewConfigurator class ConfigurableCell: UITableViewCell, ConfigurableTableViewCell { var configured = false var additionallyConfigured = false override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func configure() { self.configured = true } }
mit
Kievkao/YoutubeClassicPlayer
ClassicalPlayer/Screens/Playback/PlaybackViewController.swift
1
2658
// // PlaybackViewController.swift // ClassicalPlayer // // Created by Kravchenko, Andrii on 11/8/16. // Copyright © 2016 Kievkao. All rights reserved. // import UIKit import XCDYouTubeKit import RxFlow import RxSwift import RxCocoa final class PlaybackViewController: UIViewController { private let disposeBag = DisposeBag() @IBOutlet weak var composerNameLabel: UILabel! @IBOutlet weak var videoTitleLabel: UILabel! @IBOutlet weak var videoContainerView: UIView! fileprivate lazy var activityIndicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView() indicator.activityIndicatorViewStyle = .gray indicator.center = view.center indicator.hidesWhenStopped = true return indicator }() var viewModel: PlaybackViewModelProtocol! override func viewDidLoad() { super.viewDidLoad() bindViewModel() } private func setupUI() { composerNameLabel.text = viewModel.composerName } private func bindViewModel() { viewModel.progressSubject .bind(to: rx.progress) .disposed(by: disposeBag) viewModel.video.subscribe(onNext: { [weak self] video in guard let strongSelf = self else { return } strongSelf.videoTitleLabel.text = video.title PlaybackHolder.shared.videoController = XCDYouTubeVideoPlayerViewController() PlaybackHolder.shared.videoController.videoIdentifier = video.videoId PlaybackHolder.shared.videoController.present(in: strongSelf.videoContainerView) PlaybackHolder.shared.videoController.moviePlayer.play() strongSelf.setupUI() }).disposed(by: disposeBag) } //MARK: Actions @IBAction func previousButtonAction(_ sender: UIButton) { viewModel.getPreviousVideo() } @IBAction func nextButtonAction(_ sender: UIButton) { viewModel.getNextVideo() } } extension PlaybackViewController: StoryboardBased { static func instantiate() -> PlaybackViewController { return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PlaybackViewController") as! PlaybackViewController } } extension Reactive where Base: PlaybackViewController { var progress: Binder<Bool> { return Binder(self.base) { controller, inProgress in if inProgress { controller.activityIndicator.startAnimating() } else { controller.activityIndicator.stopAnimating() } } } }
mit
afarber/ios-newbie
TransApp/TransAppUITests/TransAppUITestsLaunchTests.swift
1
804
// // TransAppUITestsLaunchTests.swift // TransAppUITests // // Created by Alexander Farber on 05.12.21. // import XCTest class TransAppUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
unlicense
alberttra/A-Framework
Pod/Classes/AnimationServices.swift
1
184
// // AnimationService.swift // Pods // // Created by Albert Tra on 03/03/16. // // import Foundation extension UIView: Fadeable {} /// ff | 2D66CF90-3C98-4A49-A966-DBD29E6ADA6C
mit
samodom/FoundationSwagger
FoundationSwagger/Object/TypedAssociationAccessors.swift
1
6210
// // TypedAssociationAccessors.swift // FoundationSwagger // // Created by Sam Odom on 11/21/16. // Copyright © 2016 Swagger Soft. All rights reserved. // public extension AssociatingObject { /// Typed method for associated boolean values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated boolean value or `nil` if no such boolean association exists. public func booleanAssociation(for key: ObjectAssociationKey) -> Bool? { return association(for: key) as? Bool } /// Typed method for associated signed integer values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated signed integer value or `nil` if no such signed integer /// association exists. public func integerAssociation(for key: ObjectAssociationKey) -> Int? { return association(for: key) as? Int } /// Typed method for associated unsigned integer values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated unsigned integer value or `nil` if no such unsigned integer /// association exists. public func unsignedIntegerAssociation(for key: ObjectAssociationKey) -> UInt? { return association(for: key) as? UInt } /// Typed method for associated float values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated float value or `nil` if no such float association exists. public func floatAssociation(for key: ObjectAssociationKey) -> Float? { return association(for: key) as? Float } /// Typed method for associated double values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated double value or `nil` if no such double association exists. public func doubleAssociation(for key: ObjectAssociationKey) -> Double? { return association(for: key) as? Double } /// Typed method for associated string values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated string value or `nil` if no such string association exists. public func stringAssociation(for key: ObjectAssociationKey) -> String? { return association(for: key) as? String } /// Typed method for associated URL values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated URL value or `nil` if no such URL association exists. public func urlAssociation(for key: ObjectAssociationKey) -> URL? { return association(for: key) as? URL } /// Typed method for associated URL values with a default value to use. /// - parameter for: The key for the association to retrieve. /// - parameter defaultValue: URL value to use when the URL association does not exist. /// - returns: The associated URL value or `defaultValue` if no such URL association exists. public func urlAssociation(for key: ObjectAssociationKey, defaultValue: URL) -> URL { return urlAssociation(for: key) ?? defaultValue } } public extension AssociatingClass { /// Typed method for associated boolean values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated boolean value or `nil` if no such boolean association exists. public static func booleanAssociation(for key: ObjectAssociationKey) -> Bool? { return association(for: key) as? Bool } /// Typed method for associated signed integer values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated signed integer value or `nil` if no such signed integer /// association exists. public static func integerAssociation(for key: ObjectAssociationKey) -> Int? { return association(for: key) as? Int } /// Typed method for associated unsigned integer values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated unsigned integer value or `nil` if no such unsigned integer /// association exists. public static func unsignedIntegerAssociation(for key: ObjectAssociationKey) -> UInt? { return association(for: key) as? UInt } /// Typed method for associated float values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated float value or `nil` if no such float association exists. public static func floatAssociation(for key: ObjectAssociationKey) -> Float? { return association(for: key) as? Float } /// Typed method for associated double values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated double value or `nil` if no such double association exists. public static func doubleAssociation(for key: ObjectAssociationKey) -> Double? { return association(for: key) as? Double } /// Typed method for associated string values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated string value or `nil` if no such string association exists. public static func stringAssociation(for key: ObjectAssociationKey) -> String? { return association(for: key) as? String } /// Typed method for associated URL values. /// - parameter for: The key for the association to retrieve. /// - returns: The associated URL value or `nil` if no such URL association exists. public static func urlAssociation(for key: ObjectAssociationKey) -> URL? { return association(for: key) as? URL } /// Typed method for associated URL values with a default value to use. /// - parameter for: The key for the association to retrieve. /// - parameter defaultValue: URL value to use when the URL association does not exist. /// - returns: The associated URL value or `defaultValue` if no such URL association exists. public static func urlAssociation(for key: ObjectAssociationKey, defaultValue: URL) -> URL { return urlAssociation(for: key) ?? defaultValue } }
mit
ochan1/OC-PublicCode
Sections Practice/Sections Practice/ViewController.swift
1
2037
// // ViewController.swift // Sections Practice // // Created by Oscar Chan on 6/29/17. // Copyright © 2017 Oscar Chan. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let sectionTitles: [String] = ["In Progress", "Completed", "Others"] let s1Data: [String] = ["Row 1", "Row 2", "Row 3"] let s2Data: [String] = ["Row 1", "Row 2", "Row 3"] let s3Data: [String] = ["Row 1", "Row 2", "Row 3"] var sectionData: [Int: [String]] = [:] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self sectionData = [0:s1Data, 1:s2Data, 2:s3Data] } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (sectionData[section]?.count)! } /* func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] } */ func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView() // let label = UILabel() // label.text = sectionTitles[section] // label.frame = CGRect(x: 45, y: 5, width: 100, height: 35) // view.addSubview(label) return view } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 45 } func numberOfSections(in tableView: UITableView) -> Int { return sectionTitles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "cell"); } cell!.textLabel?.text = sectionData[indexPath.section]![indexPath.row] return cell! } }
mit
chrisjmendez/swift-exercises
Transitions/Razzle/Razzle/AppDelegate.swift
1
2136
// // AppDelegate.swift // Razzle // // Created by Chris on 1/20/16. // Copyright © 2016 Chris Mendez. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
CalebKierum/SwiftSoundManager
Example Project/SoundManager/GameScene.swift
1
4609
// // GameScene.swift // SoundManager // // Created by Caleb Kierum on 3/30/16. // Copyright (c) 2016 Broccoli Presentations. All rights reserved. // import SpriteKit class GameScene: SKScene { var b1 = Button(imageNamed: "play.png") var b2 = Button(imageNamed: "play.png") var b3 = Button(imageNamed: "play.png") var switchB = Button(imageNamed: "play.png") var death = Button(imageNamed: "play.png") var game = Button(imageNamed: "play.png") var width:CGFloat = 0 var height:CGFloat = 0 override func didMoveToView(view: SKView) { width = view.frame.size.width height = view.frame.size.height _prepB(b1) _prepB(b2) _prepB(b3) b1.position = CGPointMake(width / 4, height / 2) b1.text("Growl") b2.position = CGPointMake((width / 4) * 2, height / 2) b2.text("Growl2") b3.position = CGPointMake((width / 4) * 3, height / 2) b3.text("Marimba") _prepB(switchB) _prepB(death) _prepB(game) switchB.position = CGPointMake(width / 2, height - (height / 6)) switchB.text("Switch!") death.position = CGPointMake((width / 3) * 2, height / 6) death.text("Death") game.position = CGPointMake((width / 3), height / 6) game.text("Game") Sequencer.begin(false) SoundEffects.addEffect("Growl1", fileName: "se2", type: "wav") var volumeDown = SoundSettings() volumeDown.setVolume(0.5) SoundEffects.addEffect("Growl2", fileName: "se3", type: "wav", settings: volumeDown) SoundEffects.addEffect("Marimba", fileName: "se1", type: "wav", playsFrequently: true) } func _prepB(obj: SKSpriteNode) { obj.size = CGSizeMake((height / 10) * 4, height / 6) self.addChild(obj) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let p = touches.first!.locationInNode(self) b1.checkClick(p) b2.checkClick(p) b3.checkClick(p) switchB.checkClick(p) game.checkClick(p) death.checkClick(p) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { let p = touches.first!.locationInNode(self) if (b1.up(p)) { SoundEffects.play("Growl1") } if (b2.up(p)) { SoundEffects.play("Growl2") } if (b3.up(p)) { SoundEffects.play("Marimba") print("Marimba") } if (switchB.up(p)) { Sequencer.toggle() } if (game.up(p)) { Sequencer.game() } if (death.up(p)) { Sequencer.death() } } } class Button:SKSpriteNode { private var down:Bool = false private var label:SKLabelNode? private func text(message: String) { label?.removeFromParent() let newThing = SKLabelNode(fontNamed: "ArialHebrew-Bold") newThing.text = message newThing.fontSize = self.size.height * 0.5 newThing.fontColor = UIColor.blackColor() newThing.zPosition += 10 newThing.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.Center newThing.verticalAlignmentMode = SKLabelVerticalAlignmentMode.Center self.addChild(newThing) label = newThing } private func checkClick(pos: CGPoint) -> Bool { if (self.alpha > 0.9) { let left = position.x - (size.width / 2.0) let right = position.x + (size.width / 2.0) let top = position.y + (size.height / 2.0) let bottom = position.y - (size.height / 2.0) let c1 = (left < pos.x) && (pos.x < right) let c2 = (bottom < pos.y) && (pos.y < top) down = c1 && c2 return down } return false } private func shade() { if (down) { color = UIColor.blackColor() colorBlendFactor = 0.2 } } private func unshade() { colorBlendFactor = 0.0 } func down(pos: CGPoint) { if (checkClick(pos)) { shade() } } func up(pos: CGPoint) -> Bool { unshade() if (down && checkClick(pos)) { return true } return false } }
mit
ChrisLTD/vimari
app_extension/vimari/extension/SafariExtensionHandler.swift
1
2182
// // SafariExtensionHandler.swift // extension // // Created by simeg on 2018-07-13. // Copyright © 2018 vimari. All rights reserved. // import SafariServices enum ActionType: String { case openLinkInTab case openNewTab } class SafariExtensionHandler: SFSafariExtensionHandler { override func messageReceived(withName messageName: String, from page: SFSafariPage, userInfo: [String : Any]?) { switch messageName { case ActionType.openLinkInTab.rawValue: let url = URL(string: userInfo?["url"] as! String) openInNewTab(url: url!) break case ActionType.openNewTab.rawValue: openNewTab() break default: NSLog("Received message with unsupported type: \(messageName)") } } func openInNewTab(url: URL) { SFSafariApplication.getActiveWindow(completionHandler: { $0?.openTab(with: url, makeActiveIfPossible: false, completionHandler: {_ in // Perform some action here after the page loads }) }) } func openNewTab() { // Ideally this URL would be something that represents an empty tab better than localhost let url = URL(string: "http://localhost")! SFSafariApplication.getActiveWindow(completionHandler: { $0?.openTab(with: url, makeActiveIfPossible: true, completionHandler: {_ in // Perform some action here after the page loads }) }) } override func toolbarItemClicked(in window: SFSafariWindow) { // This method will be called when your toolbar item is clicked. NSLog("The extension's toolbar item was clicked") } override func validateToolbarItem(in window: SFSafariWindow, validationHandler: @escaping ((Bool, String) -> Void)) { // This is called when Safari's state changed in some way that would require the extension's toolbar item to be validated again. validationHandler(true, "") } override func popoverViewController() -> SFSafariExtensionViewController { return SafariExtensionViewController.shared } }
mit
qq565999484/RXSwiftDemo
SWIFT_RX_RAC_Demo/SWIFT_RX_RAC_Demo/RegisterViewController.swift
1
6318
// // RegisterViewController.swift // SWIFT_RX_RAC_Demo // -----------------------分割线来袭----------------------- // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // .' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // 佛祖镇楼 BUG辟易 // 佛曰: // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? // -----------------------分割线来袭----------------------- // // Created by chenyihang on 2017/6/6. // Copyright © 2017年 chenyihang. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif extension String{ var trim: String { let whitespace = NSCharacterSet.whitespacesAndNewlines var tempArray = self.components(separatedBy: whitespace) tempArray = tempArray.filter{ $0 != "" } return tempArray.joined() } } class RegisterViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var passwordLabel: UILabel! @IBOutlet weak var repeatPasswordTextField: UITextField! @IBOutlet weak var repeatPasswordLabel: UILabel! @IBOutlet weak var registerButton: UIButton! @IBOutlet weak var loginButton: UIBarButtonItem! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let viewModel = RegisterViewModel() //原来那个方法是给 TF设定绑定事件 //将TF的文本观察者绑定到VM的username上 usernameTextField.rx.text.orEmpty .bind(to: viewModel.username) .addDisposableTo(disposeBag) usernameTextField.rx.text.orEmpty.subscribe { (text) in print(text.element!.trim.characters.count) print(text.element!.characters.count) }.addDisposableTo(disposeBag) passwordTextField.rx.text.orEmpty .bind(to: viewModel.password) .addDisposableTo(disposeBag) repeatPasswordTextField.rx.text.orEmpty .bind(to: viewModel.repeartPassword) .addDisposableTo(disposeBag) registerButton.rx.tap .bind(to:viewModel.registerTaps) .addDisposableTo(disposeBag) viewModel.usernameUsable .bind(to: usernameLabel.rx.validationResult) .addDisposableTo(disposeBag) viewModel.usernameUsable .bind(to: passwordTextField.rx.inputEnabled) .addDisposableTo(disposeBag) viewModel.passwordUsable .bind(to: passwordLabel.rx.validationResult) .addDisposableTo(disposeBag) viewModel.passwordUsable .bind(to: repeatPasswordTextField.rx.inputEnabled) .addDisposableTo(disposeBag) viewModel.repeatPasswordUsable .bind(to: repeatPasswordLabel.rx.validationResult) .addDisposableTo(disposeBag) viewModel.registerButtonEnabled .subscribe(onNext:{[unowned self] valid in self.registerButton.isEnabled = valid self.registerButton.alpha = valid ? 1.0 : 0.5 }) .addDisposableTo(disposeBag) viewModel.registerResult .subscribe(onNext:{[unowned self] result in switch result{ case let .ok(message): self.showAlert(message: message) case .empty: self.showAlert(message: "") case let .failed(message): self.showAlert(message: message) } }) .addDisposableTo(disposeBag) viewModel.registerResult .bind(to: loginButton.rx.tapEnabled) .addDisposableTo(disposeBag) // Do any additional setup after loading the view. } open func showAlert(message: String) { let action = UIAlertAction(title: "确定", style: .default, handler: nil) let alertViewController = UIAlertController(title: nil, message: message, preferredStyle: .alert) alertViewController.addAction(action) present(alertViewController, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
koke/WordPressComKit
WordPressComKit/AuthenticationService.swift
1
164
import Foundation public class AuthenticationService { public func authorizeClient() { } public func fetchOAuthToken() { } }
mit
BBBInc/AlzPrevent-ios
researchline/VisualDashboardTableViewCell.swift
1
425
// // VisualDashboardTableViewCell.swift // researchline // // Created by jknam on 2015. 11. 30.. // Copyright © 2015년 bbb. All rights reserved. // import UIKit class VisualDashboardTableViewCell: DashboardTableViewCell { override func awakeFromNib() { super.name = "Visual Activity" super.titleLabel.text = "Visual Activity" super.awakeFromNib() // Initialization code } }
bsd-3-clause
austinzheng/swift-compiler-crashes
fixed/23464-swift-printingdiagnosticconsumer-handlediagnostic.swift
11
230
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where B:b{let a{func a<{class A{struct A{let a=[V:
mit
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/KnowledgeDetailComponent/View Model/KnowledgeDetailSceneInteractor.swift
1
254
import EurofurenceModel import Foundation public protocol KnowledgeDetailViewModelFactory { func makeViewModel( for identifier: KnowledgeEntryIdentifier, completionHandler: @escaping (KnowledgeEntryDetailViewModel) -> Void ) }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/16107-swift-sourcemanager-getmessage.swift
11
238
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { case var println( { for c : { if true { b = [ { class case ,
mit
MoralAlberto/SlackWebAPIKit
SlackWebAPIKit/Classes/Data/DataModels/UserDataModel.swift
1
630
import Foundation import ObjectMapper public class UserDataModel: Mappable { var id: String? var teamId: String? var name: String? var deleted: Bool? var color: String? var realName: String? var profileImage: String? required public init?(map: Map) { } // Mappable public func mapping(map: Map) { id <- map["id"] teamId <- map["team_id"] name <- map["name"] deleted <- map["deleted"] color <- map["color"] realName <- map["real_name"] profileImage <- map["profile.image_48"] } }
mit
mircealungu/Zeeguu-API-iOS
ZeeguuAPI/ZeeguuAPI/Bookmark.swift
2
7504
// // Bookmark.swift // Zeeguu Reader // // Created by Jorrit Oosterhof on 03-01-16. // Copyright © 2015 Jorrit Oosterhof. // // 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. // // 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 /// The `Bookmark` class represents a bookmark. It holds the `date`, `word`, `translation` and more about the bookmark. public class Bookmark: ZGSerializable { // MARK: Properties - /// The id of this bookmark public var id: String /// The date of this bookmark public var date: NSDate /// The word that was translated public var word: String /// The language of `Bookmark.word` public var wordLanguage: String /// The translation(s) of `Bookmark.word` public var translation: [String] /// The language of `Bookmark.translation` public var translationLanguage: String /// The title of the article in which `Bookmark.word` was translated public var title: String /// The context in which `Bookmark.word` was translated public var context: String? /// The url of the article in which `Bookmark.word` was translated public var url: String // MARK: Constructors - /** Construct a new `Bookmark` object. - parameter id: The id of this bookmark - parameter title: The title of the article in which `word` was translated - parameter context: The context in which `word` was translated - parameter url: The url of the article in which `word` was translated - parameter bookmarkDate: The date of the bookmark - parameter word: The translated word - parameter wordLanguage: The language of `word` - parameter translation: The translation(s) - parameter translationLanguage: The language of `translation` */ public init(id: String, title: String, context: String? = nil, url: String, bookmarkDate: String, word: String, wordLanguage: String, translation: [String], translationLanguage: String) { self.id = id self.title = title self.context = context self.url = url self.word = word self.wordLanguage = wordLanguage self.translation = translation self.translationLanguage = translationLanguage let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "EN-US") formatter.dateFormat = "EEEE, dd MMMM y" let date = formatter.dateFromString(bookmarkDate) self.date = date! } /** Construct a new `Bookmark` object from the data in the dictionary. - parameter dictionary: The dictionary that contains the data from which to construct an `Bookmark` object. */ @objc public required init?(dictionary dict: [String : AnyObject]) { guard let id = dict["id"] as? String, title = dict["title"] as? String, url = dict["url"] as? String, date = dict["date"] as? NSDate, word = dict["word"] as? String, wordLanguage = dict["wordLanguage"] as? String, translation = dict["translation"] as? [String], translationLanguage = dict["translationLanguage"] as? String else { return nil } self.id = id self.title = title self.url = url self.date = date self.word = word self.wordLanguage = wordLanguage self.translation = translation self.translationLanguage = translationLanguage self.context = dict["context"] as? String } // MARK: Methods - /** The dictionary representation of this `Bookmark` object. - returns: A dictionary that contains all data of this `Bookmark` object. */ @objc public func dictionaryRepresentation() -> [String: AnyObject] { var dict = [String: AnyObject]() dict["id"] = self.id dict["title"] = self.title dict["url"] = self.url dict["date"] = self.date dict["word"] = self.word dict["wordLanguage"] = self.wordLanguage dict["translation"] = self.translation dict["translationLanguage"] = self.translationLanguage dict["context"] = self.context return dict } /// Deletes this bookmark. /// /// - parameter completion: A block that will receive a boolean indicating if the bookmark could be deleted or not. public func delete(completion: (success: Bool) -> Void) { ZeeguuAPI.sharedAPI().deleteBookmarkWithID(self.id) { (success) in completion(success: success) } } /// Adds a translation to this bookmark. /// /// - parameter translation: The translation to add to this bookmark. /// - parameter completion: A block that will receive a boolean indicating if the translation could be added or not. public func addTranslation(translation: String, completion: (success: Bool) -> Void) { ZeeguuAPI.sharedAPI().addNewTranslationToBookmarkWithID(self.id, translation: translation) { (success) in completion(success: success) } } /// Deletes a translation from this bookmark. /// /// - parameter translation: The translation to remove from this bookmark. /// - parameter completion: A block that will receive a boolean indicating if the translation could be deleted or not. public func deleteTranslation(translation: String, completion: (success: Bool) -> Void) { ZeeguuAPI.sharedAPI().deleteTranslationFromBookmarkWithID(self.id, translation: translation) { (success) in completion(success: success) } } /// Retrieves all translations for this bookmark. /// /// - parameter completion: A block that will receive a dictionary with the translations. public func getTranslations(completion: (dict: JSON?) -> Void) { ZeeguuAPI.sharedAPI().getTranslationsForBookmarkWithID(self.id) { (dict) in completion(dict: dict) } } }
mit
fdzsergio/Reductio
Source/Summarizer.swift
1
1334
/** This file is part of the Reductio package. (c) Sergio Fernández <fdz.sergio@gmail.com> For the full copyright and license information, please view the LICENSE file that was distributed with this source code. */ import Foundation internal final class Summarizer { private let phrases: [Sentence] private let rank = TextRank<Sentence>() init(text: String) { self.phrases = text.sentences.map(Sentence.init) } func execute() -> [String] { buildGraph() return rank.execute() .sorted { $0.1 > $1.1 } .map { $0.0.text } } private func buildGraph() { let combinations = self.phrases.combinations(length: 2) combinations.forEach { combo in add(edge: combo.first!, node: combo.last!) } } private func add(edge pivotal: Sentence, node: Sentence) { let pivotalWordCount: Float = pivotal.words.count let nodeWordCount: Float = node.words.count // calculate weight by co-occurrence of words between sentences var score: Float = pivotal.words.filter { node.words.contains($0) }.count score = score / (log(pivotalWordCount) + log(nodeWordCount)) rank.add(edge: pivotal, to: node, weight: score) rank.add(edge: node, to: pivotal, weight: score) } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/27055-swift-constraints-constraintgraph-computeconnectedcomponents.swift
1
445
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct B<T where g:a{class a{func a{.c<T if a{
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/14328-swift-sourcemanager-getmessage.swift
11
288
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func compose( ) { class d { deinit { for in x = [ { enum b { let f { return ( ) { struct d { protocol c { class case ,
mit
cnoon/swift-compiler-crashes
crashes-fuzzing/26159-llvm-foldingset-swift-structtype-nodeequals.swift
7
200
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a{struct B struct S<T:T.a
mit
cnoon/swift-compiler-crashes
fixed/15883-swift-modulefile-gettype.swift
11
207
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where h:A class A{let f=[B?
mit
vinced45/MobilePayFinder
MobilePayFinderTests/MobilePayFinderTests.swift
1
1000
// // MobilePayFinderTests.swift // MobilePayFinderTests // // Created by Vince on 5/28/16. // Copyright © 2016 45 Bit Code. All rights reserved. // import XCTest @testable import MobilePayFinder class MobilePayFinderTests: 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.measureBlock { // Put the code you want to measure the time of here. } } }
mit
Ben21hao/edx-app-ios-enterprise-new
Source/ContainerNavigationController.swift
3
2669
// // ContainerNavigationController.swift // edX // // Created by Akiva Leffert on 6/29/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit /// A controller should implement this protocol to indicate that it wants to be responsible /// for its own status bar styling instead of leaving it up to its container, which is the default /// behavior. /// It is deliberately empty and just exists so controllers can declare they want this behavior. protocol StatusBarOverriding { } /// A controller should implement this protocol to indicate that it wants to be responsible /// for its own interface orientation instead of using the defaults. /// It is deliberately empty and just exists so controllers can declare they want this behavior. @objc protocol InterfaceOrientationOverriding { } /// A simple UINavigationController subclass that can forward status bar /// queries to its children should they opt into that by implementing the ContainedNavigationController protocol class ForwardingNavigationController: UINavigationController { override func childViewControllerForStatusBarStyle() -> UIViewController? { if let controller = viewControllers.last as? StatusBarOverriding as? UIViewController { return controller } else { return super.childViewControllerForStatusBarStyle() } } override func childViewControllerForStatusBarHidden() -> UIViewController? { if let controller = viewControllers.last as? StatusBarOverriding as? UIViewController { return controller } else { return super.childViewControllerForStatusBarHidden() } } override func shouldAutorotate() -> Bool { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.shouldAutorotate() } else { return super.shouldAutorotate() } } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.supportedInterfaceOrientations() } else { return .Portrait } } override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.preferredInterfaceOrientationForPresentation() } else { return .Portrait } } }
apache-2.0
tatsu/OpenSphericalCamera
OpenSphericalCamera/LivePreviewDelegate.swift
1
2015
// // LivePreviewDelegate.swift // OpenSphericalCamera // // Created by Tatsuhiko Arai on 9/3/16. // Copyright © 2016 Tatsuhiko Arai. All rights reserved. // import Foundation class LivePreviewDelegate: NSObject, URLSessionDataDelegate { let JPEG_SOI: [UInt8] = [0xFF, 0xD8] let JPEG_EOI: [UInt8] = [0xFF, 0xD9] let completionHandler: ((Data?, URLResponse?, Error?) -> Void) var dataBuffer = Data() init(completionHandler: @escaping ((Data?, URLResponse?, Error?) -> Void)) { self.completionHandler = completionHandler } @objc func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { dataBuffer.append(data) repeat { var soi: Int? var eoi: Int? var i = 0 dataBuffer.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in while i < dataBuffer.count - 1 { if JPEG_SOI[0] == bytes[i] && JPEG_SOI[1] == bytes[i + 1] { soi = i i += 1 break } i += 1 } while i < dataBuffer.count - 1 { if JPEG_EOI[0] == bytes[i] && JPEG_EOI[1] == bytes[i + 1] { i += 1 eoi = i break } i += 1 } } guard let start = soi, let end = eoi else { return } let frameData = dataBuffer.subdata(in: start..<(end + 1)) self.completionHandler(frameData, nil, nil) dataBuffer = dataBuffer.subdata(in: (end + 1)..<dataBuffer.count) } while dataBuffer.count >= 4 } @objc func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { session.invalidateAndCancel() self.completionHandler(nil, nil, error) } }
mit
tkremenek/swift
test/stmt/async.swift
1
446
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency -disable-availability-checking // REQUIRES: concurrency func f() async -> Int { 0 } _ = await f() // expected-error{{'async' call in a function that does not support concurrency}} async let y = await f() // expected-error{{'async let' in a function that does not support concurrency}} // expected-error@-1{{'async' call in a function that does not support concurrency}}
apache-2.0
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/NodeProperties/ValueContainer.swift
3
789
// // ValueContainer.swift // lottie-swift // // Created by Brandon Withrow on 1/30/19. // import CoreGraphics import Foundation /// A container for a node value that is Typed to T. class ValueContainer<T>: AnyValueContainer { // MARK: Lifecycle init(_ value: T) { outputValue = value } // MARK: Internal private(set) var lastUpdateFrame = CGFloat.infinity fileprivate(set) var needsUpdate = true var value: Any { outputValue as Any } var outputValue: T { didSet { needsUpdate = false } } func setValue(_ value: Any, forFrame: CGFloat) { if let typedValue = value as? T { needsUpdate = false lastUpdateFrame = forFrame outputValue = typedValue } } func setNeedsUpdate() { needsUpdate = true } }
apache-2.0
airbnb/lottie-ios
Sources/Private/Model/DotLottie/DotLottieImageProvider.swift
2
2005
// // DotLottieImageProvider.swift // Lottie // // Created by Evandro Hoffmann on 20/10/22. // import Foundation #if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) import UIKit #elseif os(macOS) import AppKit #endif // MARK: - DotLottieImageProvider /// An image provider that loads the images from a DotLottieFile into memory class DotLottieImageProvider: AnimationImageProvider { // MARK: Lifecycle /// Initializes an image provider with a specific filepath. /// /// - Parameter filepath: The absolute filepath containing the images. /// init(filepath: String) { self.filepath = URL(fileURLWithPath: filepath) loadImages() } init(filepath: URL) { self.filepath = filepath loadImages() } // MARK: Internal let filepath: URL func imageForAsset(asset: ImageAsset) -> CGImage? { images[asset.name] } // MARK: Private /// This is intentionally a Dictionary instead of an NSCache. Files from a decompressed dotLottie zip archive /// are only valid are deleted after being read into memory. If we used an NSCache then the OS could evict /// the cache entries when under memory pressure, and we would have no way to reload them later. /// - Ideally we would have a way to remove image data when under memory pressure, but this would require /// re-decompressing the dotLottie file when requesting an image that has been loaded but then removed. private var images = [String: CGImage]() private func loadImages() { filepath.urls.forEach { #if os(iOS) || os(tvOS) || os(watchOS) || targetEnvironment(macCatalyst) if let data = try? Data(contentsOf: $0), let image = UIImage(data: data)?.cgImage { images[$0.lastPathComponent] = image } #elseif os(macOS) if let data = try? Data(contentsOf: $0), let image = NSImage(data: data)?.lottie_CGImage { images[$0.lastPathComponent] = image } #endif } } }
apache-2.0
danger/danger-swift
Tests/DangerDependenciesResolverTests/PackageListMakerTests.swift
1
1460
@testable import DangerDependenciesResolver import XCTest final class PackageListMakerTests: XCTestCase { func testParsesValidPackages() { let expectedResult = Package(name: "test", url: URL(string: "about:blank")!, majorVersion: 5) let expectedResult2 = Package(name: "test", url: URL(string: "about:blank")!, majorVersion: 5) let dataReader = StubbedDataReader() dataReader.stubbedReadData = { path in switch path { case "/user/franco/Package1.swift": return try expectedResult.encoded() case "/user/franco/Package2.swift": return try expectedResult.encoded() case "/user/franco/File.swift": return Data() default: XCTFail("Received invalid path \(path)") return Data() } } let fileManager = StubbedFileManager() fileManager.stubbedContent = ["Package1.swift", "File.swift", "Package2.swift"] let packageListMaker = PackageListMaker(folder: "/user/franco", fileManager: fileManager, dataReader: dataReader) let packages = packageListMaker.makePackageList() XCTAssertEqual(packages, [expectedResult, expectedResult2]) } } final class StubbedFileManager: FileManager { var stubbedContent: [String] = [] override func contentsOfDirectory(atPath _: String) throws -> [String] { stubbedContent } }
mit
Kratos28/KPageView
KPageViewSwift/KPageView/HYPageView/KPageView.swift
1
8284
// // KPageView.swift // KPageView // // Created by Kratos on 17/4/8. // Copyright © 2017年 Kratos. All rights reserved. // import UIKit protocol KPageViewDataSource : class { func numberOfSectionsInPageView(_ pageView : KPageView) -> Int func pageView(_ pageView : KPageView, numberOfItemsInSection section: Int) -> Int func pageView(_ pageView : KPageView, cellForItemAtIndexPath indexPath : IndexPath) -> UICollectionViewCell } @objc protocol KPageViewDelegate : class { @objc optional func pageView(_ pageView : KPageView, didSelectedAtIndexPath indexPath : IndexPath) } class KPageView: UIView { // 在swift中, 如果子类有自定义构造函数, 或者重新父类的构造函数, 那么必须实现父类中使用required修饰的构造函数 weak var dataSource : KPageViewDataSource? weak var delegate : KPageViewDelegate? // MARK: 定义属性 fileprivate var style : KPageStyle fileprivate var titles : [String] fileprivate var childVcs : [UIViewController]! fileprivate var parentVc : UIViewController! fileprivate var layout : KPageViewLayout! fileprivate var collectionView : UICollectionView! fileprivate var pageControl : UIPageControl! fileprivate lazy var currentSection : Int = 0 fileprivate lazy var titleView : KTitleView = { let titleFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.style.titleHeight) let titleView = KTitleView(frame: titleFrame, style: self.style, titles: self.titles) titleView.backgroundColor = UIColor.blue return titleView }() // MARK: 构造函数 init(frame: CGRect, style : KPageStyle, titles : [String], childVcs : [UIViewController], parentVc : UIViewController) { // 在super.init()之前, 需要保证所有的属性有被初始化 // self.不能省略: 在函数中, 如果和成员属性产生歧义 self.style = style self.titles = titles self.childVcs = childVcs self.parentVc = parentVc super.init(frame: frame) setupContentUI() } init(frame: CGRect, style : KPageStyle, titles : [String], layout : KPageViewLayout) { self.style = style self.titles = titles self.layout = layout super.init(frame: frame) setupCollectionUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 初始化UI界面 extension KPageView { // MARK: 初始化控制器的UI fileprivate func setupContentUI() { self.addSubview(titleView) // 1.创建KContentView let contentFrame = CGRect(x: 0, y: style.titleHeight, width: bounds.width, height: bounds.height - style.titleHeight) let contentView = KContentView(frame: contentFrame, childVcs: childVcs, parentVc : parentVc) as KContentView contentView.backgroundColor = UIColor.randomColor addSubview(contentView) // 2.让KTitleView&KContentView进行交互 titleView.delegate = contentView contentView.delegate = titleView } // MARK: 初始化collectionView的UI fileprivate func setupCollectionUI() { // 1.添加titleView self.addSubview(titleView) // 2.添加collectionView let collectionFrame = CGRect(x: 0, y: style.titleHeight, width: bounds.width, height: bounds.height - style.titleHeight - style.pageControlHeight) collectionView = UICollectionView(frame: collectionFrame, collectionViewLayout: layout) collectionView.isPagingEnabled = true collectionView.scrollsToTop = false collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self addSubview(collectionView) // 3.添加UIPageControl let pageControlFrame = CGRect(x: 0, y: collectionView.frame.maxY, width: bounds.width, height: style.pageControlHeight) pageControl = UIPageControl(frame: pageControlFrame) pageControl.numberOfPages = 4 addSubview(pageControl) pageControl.isEnabled = false // 4.监听titleView的点击 titleView.delegate = self } } // MARK:- UICollectionView的数据源 extension KPageView : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource?.numberOfSectionsInPageView(self) ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let itemCount = dataSource?.pageView(self, numberOfItemsInSection: section) ?? 0 if section == 0 { pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1 } return itemCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return dataSource!.pageView(self, cellForItemAtIndexPath: indexPath) } } extension KPageView : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.pageView?(self, didSelectedAtIndexPath: indexPath) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { collectionViewDidEndScroll() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { collectionViewDidEndScroll() } } func collectionViewDidEndScroll() { // 1.获取当前显示页中的某一个cell的indexPath let point = CGPoint(x: layout.sectionInset.left + collectionView.contentOffset.x, y: layout.sectionInset.top) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } // 2.如果发现组(section)发生了改变, 那么重新设置pageControl的numberOfPages if indexPath.section != currentSection { // 2.1.改变pageControl的numberOfPages let itemCount = dataSource?.pageView(self, numberOfItemsInSection: indexPath.section) ?? 0 pageControl.numberOfPages = (itemCount - 1) / (layout.rows * layout.cols) + 1 // 2.2.记录最新的currentSection currentSection = indexPath.section // 2.3.让titleView选中最新的title titleView.setCurrentIndex(currentIndex: currentSection) } // 3.显示pageControl正确的currentPage let pageIndex = indexPath.item / 8 pageControl.currentPage = pageIndex } } // MARK:- 实现KTitleView的代理方法 extension KPageView : KTitleViewDelegate { func titleView(_ titleView: KTitleView, currentIndex: Int) { // 1.滚动到正确的位置 let indexPath = IndexPath(item: 0, section: currentIndex) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) // 2.微调collectionView -- contentOffset collectionView.contentOffset.x -= layout.sectionInset.left // 3.改变pageControl的numberOfPages let itemCount = dataSource?.pageView(self, numberOfItemsInSection: currentIndex) ?? 0 pageControl.numberOfPages = (itemCount - 1) / (layout.rows * layout.cols) + 1 pageControl.currentPage = 0 // 4.记录最新的currentSection currentSection = currentIndex } } // MARK:- 对外提供的函数 extension KPageView { func registerCell(_ cellClass : AnyClass?, identifier : String) { collectionView.register(cellClass, forCellWithReuseIdentifier: identifier) } func registerNib(_ nib : UINib?, identifier : String) { collectionView.register(nib, forCellWithReuseIdentifier: identifier) } func dequeueReusableCell(withReuseIdentifier : String, for indexPath : IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: withReuseIdentifier, for: indexPath) } }
mit
indragiek/Ares
client/AresKit/FileTransferContext.swift
1
814
// // FileTransferContext.swift // Ares // // Created by Indragie on 1/31/16. // Copyright © 2016 Indragie Karunaratne. All rights reserved. // import Foundation private let ArchivedFilePathKey = "filePath"; public struct FileTransferContext { public let filePath: String init(filePath: String) { self.filePath = filePath } init?(data: NSData) { if let dict = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [String: AnyObject], filePath = dict[ArchivedFilePathKey] as? String { self.filePath = filePath } else { return nil } } func archive() -> NSData { let dict: NSDictionary = [ArchivedFilePathKey: filePath] return NSKeyedArchiver.archivedDataWithRootObject(dict) } }
mit
Daemon-Devarshi/MedicationSchedulerSwift3.0
Medication/DataModels/Nurse+CoreDataProperties.swift
1
901
// // Nurse+CoreDataProperties.swift // Medication // // Created by Devarshi Kulshreshtha on 9/9/16. // Copyright © 2016 Devarshi. All rights reserved. // import Foundation import CoreData extension Nurse { @nonobjc public class func fetchRequest() -> NSFetchRequest<Nurse> { return NSFetchRequest<Nurse>(entityName: "Nurse"); } @NSManaged public var email: String? @NSManaged public var password: String? @NSManaged public var patient: NSSet? } // MARK: Generated accessors for patient extension Nurse { @objc(addPatientObject:) @NSManaged public func addToPatient(_ value: Patient) @objc(removePatientObject:) @NSManaged public func removeFromPatient(_ value: Patient) @objc(addPatient:) @NSManaged public func addToPatient(_ values: NSSet) @objc(removePatient:) @NSManaged public func removeFromPatient(_ values: NSSet) }
mit
mkondakov/MovingHelper
MovingHelper/Views/TaskTableViewCell.swift
1
1231
// // TaskTableViewCell.swift // MovingHelper // // Created by Ellen Shapiro on 6/9/15. // Copyright (c) 2015 Razeware. All rights reserved. // import UIKit public class TaskTableViewCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var notesLabel: UILabel! @IBOutlet public var checkbox: Checkbox! var currentTask: Task? public var delegate: TaskUpdatedDelegate? public func configureForTask(task: Task) { currentTask = task titleLabel.text = task.title notesLabel.text = task.notes configureForDoneState(task.done) } public override func prepareForReuse() { super.prepareForReuse() currentTask = nil delegate = nil } func configureForDoneState(done: Bool) { checkbox.isChecked = done if done { backgroundColor = .lightGrayColor() titleLabel.alpha = 0.5 notesLabel.alpha = 0.5 } else { backgroundColor = .whiteColor() titleLabel.alpha = 1 notesLabel.alpha = 1 } } @IBAction func tappedCheckbox() { configureForDoneState(!checkbox.isChecked) if let task = currentTask { task.done = checkbox.isChecked delegate?.taskUpdated(task) } } }
mit
4taras4/totp-auth
TOTP/ViperModules/MainList/Module/Interactor/MainListInteractorOutput.swift
1
362
// // MainListMainListInteractorOutput.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import Foundation protocol MainListInteractorOutput: class { func listOfCodes(codes: [Code], favourites: [Code]) func dataBaseOperationFinished() func listOfFolders(array: [Folder]) }
mit
Sebastian-Hojas/FlexPomo
FlexPomo/View/StatusBarViewController.swift
1
1776
// // StatusBarViewController.swift // FlexPomo // // Created by Sebastian Hojas on 11/01/2017. // Copyright © 2017 Sebastian Hojas. All rights reserved. // import Foundation import Cocoa import ReactiveCocoa import ReactiveSwift class StatusBarViewController: NSObject { let FPS = 4.0 let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) var statusBarViewModel: StatusBarViewModel? override func awakeFromNib() { statusBarViewModel = ViewModels.shared.statusBarViewModel statusItem.button?.action = #selector(StatusBarViewController.statusBarClicked(sender:)) statusItem.button?.target = self statusItem.button?.sendAction(on: [.leftMouseUp, .rightMouseUp]) timer(interval: .milliseconds(Int(1000.0/FPS)), on: QueueScheduler(qos: .background)) .throttle(1.0/FPS, on: QueueScheduler(qos: .background)) .take(during: reactive.lifetime) .observe(on: UIScheduler()) .startWithValues { [weak self] _ in let string = self?.statusBarViewModel?.title ?? "X" let attributedString = NSMutableAttributedString(string: string) attributedString.addAttribute(NSKernAttributeName, value: 1, range: NSMakeRange(0, string.characters.count)) self?.statusItem.button?.attributedTitle = attributedString } } func statusBarClicked(sender: NSStatusBarButton) { guard let event = NSApp?.currentEvent else { return } switch event.type { case .leftMouseUp: statusBarViewModel?.action() case .rightMouseUp: print("Right click") default: break } } }
mit