repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
insidegui/WWDC
|
WWDC/AppCoordinator.swift
|
1
|
19914
|
//
// AppCoordinator.swift
// WWDC
//
// Created by Guilherme Rambo on 19/04/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RealmSwift
import RxSwift
import ConfCore
import PlayerUI
import os.log
final class AppCoordinator {
let log = OSLog(subsystem: "WWDC", category: "AppCoordinator")
private let disposeBag = DisposeBag()
var liveObserver: LiveObserver
var storage: Storage
var syncEngine: SyncEngine
var windowController: MainWindowController
var tabController: WWDCTabViewController<MainWindowTab>
var featuredController: FeaturedContentViewController
var scheduleController: ScheduleContainerViewController
var videosController: SessionsSplitViewController
var communityController: CommunityViewController
var currentPlayerController: VideoPlayerViewController?
var currentActivity: NSUserActivity?
var activeTab: MainWindowTab = .schedule
/// The tab that "owns" the current player (the one that was active when the "play" button was pressed)
var playerOwnerTab: MainWindowTab?
/// The session that "owns" the current player (the one that was selected on the active tab when "play" was pressed)
var playerOwnerSessionIdentifier: String? {
didSet { rxPlayerOwnerSessionIdentifier.onNext(playerOwnerSessionIdentifier) }
}
var rxPlayerOwnerSessionIdentifier = BehaviorSubject<String?>(value: nil)
/// Whether we're currently in the middle of a player context transition
var isTransitioningPlayerContext = false
/// Whether we were playing the video when a clip sharing session begin, to restore state later.
var wasPlayingWhenClipSharingBegan = false
init(windowController: MainWindowController, storage: Storage, syncEngine: SyncEngine) {
self.storage = storage
self.syncEngine = syncEngine
DownloadManager.shared.start(with: storage)
windowController.titleBarViewController.statusViewController = DownloadsStatusViewController(downloadManager: DownloadManager.shared, storage: storage)
liveObserver = LiveObserver(dateProvider: today, storage: storage, syncEngine: syncEngine)
// Primary UI Intialization
tabController = WWDCTabViewController(windowController: windowController)
// Featured
featuredController = FeaturedContentViewController()
featuredController.identifier = NSUserInterfaceItemIdentifier(rawValue: "Featured")
let featuredItem = NSTabViewItem(viewController: featuredController)
featuredItem.label = "Featured"
tabController.addTabViewItem(featuredItem)
// Schedule
scheduleController = ScheduleContainerViewController(windowController: windowController, listStyle: .schedule)
scheduleController.identifier = NSUserInterfaceItemIdentifier(rawValue: "Schedule")
scheduleController.splitViewController.splitView.identifier = NSUserInterfaceItemIdentifier(rawValue: "ScheduleSplitView")
scheduleController.splitViewController.splitView.autosaveName = "ScheduleSplitView"
let scheduleItem = NSTabViewItem(viewController: scheduleController)
scheduleItem.label = "Schedule"
scheduleItem.initialFirstResponder = scheduleController.splitViewController.listViewController.tableView
tabController.addTabViewItem(scheduleItem)
// Videos
videosController = SessionsSplitViewController(windowController: windowController, listStyle: .videos)
videosController.identifier = NSUserInterfaceItemIdentifier(rawValue: "Videos")
videosController.splitView.identifier = NSUserInterfaceItemIdentifier(rawValue: "VideosSplitView")
videosController.splitView.autosaveName = "VideosSplitView"
let videosItem = NSTabViewItem(viewController: videosController)
videosItem.label = "Videos"
videosItem.initialFirstResponder = videosController.listViewController.tableView
tabController.addTabViewItem(videosItem)
// Community
communityController = CommunityViewController(syncEngine: syncEngine)
communityController.identifier = NSUserInterfaceItemIdentifier(rawValue: "Community")
let communityItem = NSTabViewItem(viewController: communityController)
communityItem.label = "Community"
tabController.addTabViewItem(communityItem)
self.windowController = windowController
restoreApplicationState()
setupBindings()
setupDelegation()
_ = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: nil) { _ in self.saveApplicationState() }
_ = NotificationCenter.default.addObserver(forName: .RefreshPeriodicallyPreferenceDidChange, object: nil, queue: nil, using: { _ in self.resetAutorefreshTimer() })
_ = NotificationCenter.default.addObserver(forName: .PreferredTranscriptLanguageDidChange, object: nil, queue: .main, using: { self.preferredTranscriptLanguageDidChange($0) })
NSApp.isAutomaticCustomizeTouchBarMenuItemEnabled = true
}
/// The list controller for the active tab
var currentListController: SessionsTableViewController? {
switch activeTab {
case .schedule:
return scheduleController.splitViewController.listViewController
case .videos:
return videosController.listViewController
default:
return nil
}
}
/// The session that is currently selected on the videos tab (observable)
var selectedSession: Observable<SessionViewModel?> {
return videosController.listViewController.selectedSession.asObservable()
}
/// The session that is currently selected on the schedule tab (observable)
var selectedScheduleItem: Observable<SessionViewModel?> {
return scheduleController.splitViewController.listViewController.selectedSession.asObservable()
}
/// The session that is currently selected on the videos tab
var selectedSessionValue: SessionViewModel? {
return videosController.listViewController.selectedSession.value
}
/// The session that is currently selected on the schedule tab
var selectedScheduleItemValue: SessionViewModel? {
return scheduleController.splitViewController.listViewController.selectedSession.value
}
/// The selected session's view model, regardless of which tab it is selected in
var selectedViewModelRegardlessOfTab: SessionViewModel?
/// The viewModel for the current playback session
var currentPlaybackViewModel: PlaybackViewModel? {
didSet {
observeNowPlayingInfo()
}
}
private func setupBindings() {
tabController.rxActiveTab.subscribe(onNext: { [weak self] activeTab in
self?.activeTab = activeTab
self?.updateSelectedViewModelRegardlessOfTab()
}).disposed(by: disposeBag)
func bind(session: Observable<SessionViewModel?>, to detailsController: SessionDetailsViewController) {
session.subscribe(on: MainScheduler.instance).subscribe(onNext: { [weak self] viewModel in
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.35
detailsController.viewModel = viewModel
self?.updateSelectedViewModelRegardlessOfTab()
})
}).disposed(by: disposeBag)
}
bind(session: selectedSession, to: videosController.detailViewController)
bind(session: selectedScheduleItem, to: scheduleController.splitViewController.detailViewController)
}
private func updateSelectedViewModelRegardlessOfTab() {
switch activeTab {
case .schedule:
selectedViewModelRegardlessOfTab = selectedScheduleItemValue
case .videos:
selectedViewModelRegardlessOfTab = selectedSessionValue
default:
selectedViewModelRegardlessOfTab = nil
}
updateShelfBasedOnSelectionChange()
updateCurrentActivity(with: selectedViewModelRegardlessOfTab)
}
func selectSessionOnAppropriateTab(with viewModel: SessionViewModel) {
if currentListController?.canDisplay(session: viewModel) == true {
currentListController?.select(session: viewModel)
return
}
if videosController.listViewController.canDisplay(session: viewModel) {
videosController.listViewController.select(session: viewModel)
tabController.activeTab = .videos
} else if scheduleController.splitViewController.listViewController.canDisplay(session: viewModel) {
scheduleController.splitViewController.listViewController.select(session: viewModel)
tabController.activeTab = .schedule
}
}
private func setupDelegation() {
let videoDetail = videosController.detailViewController
videoDetail.shelfController.delegate = self
videoDetail.summaryController.actionsViewController.delegate = self
videoDetail.summaryController.relatedSessionsViewController.delegate = self
let scheduleDetail = scheduleController.splitViewController.detailViewController
scheduleDetail.shelfController.delegate = self
scheduleDetail.summaryController.actionsViewController.delegate = self
scheduleDetail.summaryController.relatedSessionsViewController.delegate = self
videosController.listViewController.delegate = self
scheduleController.splitViewController.listViewController.delegate = self
featuredController.delegate = self
}
private func updateListsAfterSync() {
doUpdateLists()
DownloadManager.shared.syncWithFileSystem()
}
private func doUpdateLists() {
// Initial app launch waits for all of these things to be loaded before dismissing the primary loading spinner
// It may, however, delay the presentation of content on tabs that already have everything they need
let startupDependencies = Observable.combineLatest(storage.tracksObservable,
storage.eventsObservable,
storage.focusesObservable,
storage.scheduleObservable,
storage.featuredSectionsObservable)
startupDependencies
.filter {
!$0.0.isEmpty && !$0.1.isEmpty && !$0.2.isEmpty && !$0.4.isEmpty
}
.take(1)
.subscribe(onNext: { [weak self] tracks, _, _, sections, _ in
guard let self = self else { return }
self.tabController.hideLoading()
self.searchCoordinator.configureFilters()
self.videosController.listViewController.sessionRowProvider = VideosSessionRowProvider(tracks: tracks)
self.scheduleController.splitViewController.listViewController.sessionRowProvider = ScheduleSessionRowProvider(scheduleSections: sections)
self.scrollToTodayIfWWDC()
}).disposed(by: disposeBag)
bindScheduleAvailability()
liveObserver.start()
}
private func bindScheduleAvailability() {
storage.eventHeroObservable.map({ $0 != nil })
.bind(to: scheduleController.showHeroView)
.disposed(by: disposeBag)
storage.eventHeroObservable.bind(to: scheduleController.heroController.hero)
.disposed(by: disposeBag)
}
private func updateFeaturedSectionsAfterSync() {
storage
.featuredSectionsObservable
.filter { !$0.isEmpty }
.subscribe(on: MainScheduler.instance)
.take(1)
.subscribe(onNext: { [weak self] sections in
self?.featuredController.sections = sections.map { FeaturedSectionViewModel(section: $0) }
}).disposed(by: disposeBag)
}
private lazy var searchCoordinator: SearchCoordinator = {
return SearchCoordinator(self.storage,
sessionsController: self.scheduleController.splitViewController.listViewController,
videosController: self.videosController.listViewController,
restorationFiltersState: Preferences.shared.filtersState)
}()
func startup() {
RemoteEnvironment.shared.start()
ContributorsFetcher.shared.load()
windowController.contentViewController = tabController
windowController.showWindow(self)
if storage.isEmpty {
tabController.showLoading()
}
func checkSyncEngineOperationSucceededAndShowError(note: Notification) -> Bool {
if let error = note.object as? APIError {
switch error {
case .adapter, .unknown:
WWDCAlert.show(with: error)
case .http:()
}
} else if let error = note.object as? Error {
WWDCAlert.show(with: error)
} else {
return true
}
return false
}
_ = NotificationCenter.default.addObserver(forName: .SyncEngineDidSyncSessionsAndSchedule, object: nil, queue: .main) { note in
guard checkSyncEngineOperationSucceededAndShowError(note: note) else { return }
self.updateListsAfterSync()
}
_ = NotificationCenter.default.addObserver(forName: .SyncEngineDidSyncFeaturedSections, object: nil, queue: .main) { note in
guard checkSyncEngineOperationSucceededAndShowError(note: note) else { return }
self.updateFeaturedSectionsAfterSync()
}
_ = NotificationCenter.default.addObserver(forName: .WWDCEnvironmentDidChange, object: nil, queue: .main) { _ in
self.refresh(nil)
}
refresh(nil)
updateListsAfterSync()
updateFeaturedSectionsAfterSync()
if Arguments.showPreferences {
showPreferences(nil)
}
}
@discardableResult func receiveNotification(with userInfo: [String: Any]) -> Bool {
let userDataSyncEngineHandled: Bool
#if ICLOUD
userDataSyncEngineHandled = syncEngine.userDataSyncEngine?.processSubscriptionNotification(with: userInfo) == true
#else
userDataSyncEngineHandled = false
#endif
return userDataSyncEngineHandled ||
liveObserver.processSubscriptionNotification(with: userInfo) ||
RemoteEnvironment.shared.processSubscriptionNotification(with: userInfo)
}
// MARK: - Now playing info
private var nowPlayingInfoBag = DisposeBag()
private func observeNowPlayingInfo() {
nowPlayingInfoBag = DisposeBag()
currentPlaybackViewModel?.nowPlayingInfo.asObservable().subscribe(onNext: { [weak self] _ in
self?.publishNowPlayingInfo()
}).disposed(by: nowPlayingInfoBag)
}
// MARK: - State restoration
private func saveApplicationState() {
Preferences.shared.activeTab = activeTab
Preferences.shared.selectedScheduleItemIdentifier = selectedScheduleItemValue?.identifier
Preferences.shared.selectedVideoItemIdentifier = selectedSessionValue?.identifier
Preferences.shared.filtersState = searchCoordinator.currentFiltersState()
}
private func restoreApplicationState() {
let activeTab = Preferences.shared.activeTab
tabController.activeTab = activeTab
if let identifier = Preferences.shared.selectedScheduleItemIdentifier {
scheduleController.splitViewController.listViewController.select(session: SessionIdentifier(identifier))
}
if let identifier = Preferences.shared.selectedVideoItemIdentifier {
videosController.listViewController.select(session: SessionIdentifier(identifier))
}
}
private func scrollToTodayIfWWDC() {
guard liveObserver.isWWDCWeek else { return }
scheduleController.splitViewController.listViewController.scrollToToday()
}
// MARK: - Deep linking
func handle(link: DeepLink) {
if link.isForCurrentYear {
tabController.activeTab = .schedule
scheduleController.splitViewController.listViewController.select(session: SessionIdentifier(link.sessionIdentifier))
} else {
tabController.activeTab = .videos
videosController.listViewController.select(session: SessionIdentifier(link.sessionIdentifier))
}
}
// MARK: - Preferences
private lazy var preferencesCoordinator: PreferencesCoordinator = {
PreferencesCoordinator(syncEngine: syncEngine)
}()
func showPreferences(_ sender: Any?) {
#if ICLOUD
preferencesCoordinator.userDataSyncEngine = syncEngine.userDataSyncEngine
#endif
preferencesCoordinator.show()
}
// MARK: - About window
fileprivate lazy var aboutWindowController: AboutWindowController = {
var aboutWC = AboutWindowController(infoText: ContributorsFetcher.shared.infoText)
ContributorsFetcher.shared.infoTextChangedCallback = { [unowned self] newText in
self.aboutWindowController.infoText = newText
}
return aboutWC
}()
func showAboutWindow() {
aboutWindowController.showWindow(nil)
}
func showFeatured() {
tabController.activeTab = .featured
}
func showSchedule() {
tabController.activeTab = .schedule
}
func showVideos() {
tabController.activeTab = .videos
}
func showCommunity() {
tabController.activeTab = .community
}
// MARK: - Refresh
/// Used to prevent the refresh system from being spammed. Resetting
/// NSBackgroundActivitySchedule can result in the scheduled activity happening immediately
/// especially if the `interval` is sufficiently low.
private var lastRefresh = Date.distantPast
func refresh(_ sender: Any?) {
let now = Date()
guard now.timeIntervalSince(lastRefresh) > 5 else { return }
lastRefresh = now
DispatchQueue.main.async {
self.syncEngine.syncConfiguration()
self.syncEngine.syncContent()
self.syncEngine.syncCommunityContent()
self.liveObserver.refresh()
if self.autorefreshActivity == nil
|| (sender as? NSBackgroundActivityScheduler) !== self.autorefreshActivity {
self.resetAutorefreshTimer()
}
}
}
private var autorefreshActivity: NSBackgroundActivityScheduler?
func makeAutorefreshActivity() -> NSBackgroundActivityScheduler {
let activityScheduler = NSBackgroundActivityScheduler(identifier: "io.wwdc.autorefresh.backgroundactivity")
activityScheduler.interval = Constants.autorefreshInterval
activityScheduler.repeats = true
activityScheduler.qualityOfService = .utility
activityScheduler.schedule { [weak self] completion in
self?.refresh(self?.autorefreshActivity)
completion(.finished)
}
return activityScheduler
}
private func resetAutorefreshTimer() {
autorefreshActivity?.invalidate()
autorefreshActivity = Preferences.shared.refreshPeriodically ? makeAutorefreshActivity() : nil
}
// MARK: - Language preference
private func preferredTranscriptLanguageDidChange(_ note: Notification) {
guard let code = note.object as? String else { return }
syncEngine.transcriptLanguage = code
}
}
|
bsd-2-clause
|
9c8f3918f83d56197bbe223918dd42fb
| 37.07457 | 183 | 0.688344 | 5.681312 | false | false | false | false |
ahoppen/swift
|
test/decl/protocol/req/missing_conformance.swift
|
4
|
6842
|
// RUN: %target-typecheck-verify-swift
// Test candidates for witnesses that are missing conformances
// in various ways.
protocol LikeSetAlgebra {
func onion(_ other: Self) -> Self // expected-note {{protocol requires function 'onion' with type '(X) -> X'; do you want to add a stub?}}
func indifference(_ other: Self) -> Self // expected-note {{protocol requires function 'indifference' with type '(X) -> X'; do you want to add a stub?}}
}
protocol LikeOptionSet : LikeSetAlgebra, RawRepresentable {}
extension LikeOptionSet where RawValue : FixedWidthInteger {
func onion(_ other: Self) -> Self { return self } // expected-note {{candidate would match if 'X.RawValue' conformed to 'FixedWidthInteger'}}
func indifference(_ other: Self) -> Self { return self } // expected-note {{candidate would match if 'X.RawValue' conformed to 'FixedWidthInteger'}}
}
struct X : LikeOptionSet {}
// expected-error@-1 {{type 'X' does not conform to protocol 'LikeSetAlgebra'}}
// expected-error@-2 {{type 'X' does not conform to protocol 'RawRepresentable'}}
protocol IterProtocol {}
protocol LikeSequence {
associatedtype Iter : IterProtocol // expected-note {{unable to infer associated type 'Iter' for protocol 'LikeSequence'}}
func makeIter() -> Iter
}
extension LikeSequence where Self == Self.Iter {
func makeIter() -> Self { return self } // expected-note {{candidate would match and infer 'Iter' = 'Y' if 'Y' conformed to 'IterProtocol'}}
}
struct Y : LikeSequence {} // expected-error {{type 'Y' does not conform to protocol 'LikeSequence'}}
protocol P1 {
associatedtype Result
func get() -> Result // expected-note {{protocol requires function 'get()' with type '() -> Result'; do you want to add a stub?}}
func got() // expected-note {{protocol requires function 'got()' with type '() -> ()'; do you want to add a stub?}}
}
protocol P2 {
static var singularThing: Self { get }
}
extension P1 where Result : P2 {
func get() -> Result { return Result.singularThing } // expected-note {{candidate would match if 'Result' conformed to 'P2'}}
}
protocol P3 {}
extension P1 where Self : P3 {
func got() {} // expected-note {{candidate would match if 'Z<T1, T2, T3, Result, T4>' conformed to 'P3'}}
}
struct Z<T1, T2, T3, Result, T4> : P1 {} // expected-error {{type 'Z<T1, T2, T3, Result, T4>' does not conform to protocol 'P1'}}
protocol P4 {
func this() // expected-note 2 {{protocol requires function 'this()' with type '() -> ()'; do you want to add a stub?}}
}
protocol P5 {}
extension P4 where Self : P5 {
func this() {} // expected-note {{candidate would match if 'W' conformed to 'P5'}}
//// expected-note@-1 {{candidate would match if 'S<T>.SS' conformed to 'P5'}}
}
struct W : P4 {} // expected-error {{type 'W' does not conform to protocol 'P4'}}
struct S<T> {
struct SS : P4 {} // expected-error {{type 'S<T>.SS' does not conform to protocol 'P4'}}
}
class C {}
protocol P6 {
associatedtype T : C // expected-note {{unable to infer associated type 'T' for protocol 'P6'}}
func f(t: T)
}
struct A : P6 { // expected-error {{type 'A' does not conform to protocol 'P6'}}
func f(t: Int) {} // expected-note {{candidate can not infer 'T' = 'Int' because 'Int' is not a class type and so can't inherit from 'C'}}
}
protocol P7 {}
protocol P8 {
associatedtype T : P7 // expected-note {{unable to infer associated type 'T' for protocol 'P8'}}
func g(t: T)
}
struct B : P8 { // expected-error {{type 'B' does not conform to protocol 'P8'}}
func g(t: (Int, String)) {} // expected-note {{candidate can not infer 'T' = '(Int, String)' because '(Int, String)' is not a nominal type and so can't conform to 'P7'}}
}
protocol P9 {
func foo() // expected-note {{protocol requires function 'foo()' with type '() -> ()'; do you want to add a stub?}}
}
class C2 {}
extension P9 where Self : C2 {
func foo() {} // expected-note {{candidate would match if 'C3' subclassed 'C2'}}
}
class C3 : P9 {} // expected-error {{type 'C3' does not conform to protocol 'P9'}}
protocol P10 {
associatedtype A
func bar() // expected-note {{protocol requires function 'bar()' with type '() -> ()'; do you want to add a stub?}}
}
extension P10 where A == Int {
func bar() {} // expected-note {{candidate would match if 'A' was the same type as 'Int'}}
}
struct S2<A> : P10 {} // expected-error {{type 'S2<A>' does not conform to protocol 'P10'}}
protocol P11 {}
protocol P12 {
associatedtype A : P11 // expected-note {{unable to infer associated type 'A' for protocol 'P12'}}
func bar() -> A
}
extension Int : P11 {}
struct S3 : P12 { // expected-error {{type 'S3' does not conform to protocol 'P12'}}
func bar() -> P11 { return 0 }
// expected-note@-1 {{cannot infer 'A' = 'any P11' because 'any P11' as a type cannot conform to protocols; did you mean to use an opaque result type?}}{{19-19=some }}
}
protocol P13 {
associatedtype A : P11 // expected-note {{unable to infer associated type 'A' for protocol 'P13'}}
var bar: A { get }
}
struct S4: P13 { // expected-error {{type 'S4' does not conform to protocol 'P13'}}
var bar: P11 { return 0 }
// expected-note@-1 {{cannot infer 'A' = 'any P11' because 'any P11' as a type cannot conform to protocols; did you mean to use an opaque result type?}}{{12-12=some }}
}
protocol P14 {
associatedtype A : P11 // expected-note {{unable to infer associated type 'A' for protocol 'P14'}}
subscript(i: Int) -> A { get }
}
struct S5: P14 { // expected-error {{type 'S5' does not conform to protocol 'P14'}}
subscript(i: Int) -> P11 { return i }
// expected-note@-1 {{cannot infer 'A' = 'any P11' because 'any P11' as a type cannot conform to protocols; did you mean to use an opaque result type?}}{{24-24=some }}
}
// SR-12759
struct CountSteps1<T> : Collection {
init(count: Int) { self.count = count }
var count: Int
var startIndex: Int { 0 }
var endIndex: Int { count }
func index(after i: Int) -> Int {
totalSteps += 1 // expected-error {{cannot find 'totalSteps' in scope}}
return i + 1
}
subscript(i: Int) -> Int { return i }
}
extension CountSteps1 // expected-error {{type 'CountSteps1<T>' does not conform to protocol 'RandomAccessCollection'}}
// expected-error@-1 {{conditional conformance of type 'CountSteps1<T>' to protocol 'RandomAccessCollection' does not imply conformance to inherited protocol 'BidirectionalCollection'}}
// expected-note@-2 {{did you mean to explicitly state the conformance like 'extension CountSteps1: BidirectionalCollection where ...'?}}
// expected-error@-3 {{type 'CountSteps1<T>' does not conform to protocol 'BidirectionalCollection'}}
: RandomAccessCollection
where T : Equatable
{
typealias Index = Int
func index(_ i: Index, offsetBy d: Int) -> Index {
return i + d
}
}
|
apache-2.0
|
bcbffc36c7b64edcb1b7822edd52265f
| 42.031447 | 187 | 0.666618 | 3.616279 | false | false | false | false |
yuyedaidao/YQRefresh
|
Classes/YQRefresher.swift
|
1
|
5112
|
//
// YQRefreshable.swift
// YQRefresh
//
// Created by 王叶庆 on 2017/2/10.
// Copyright © 2017年 王叶庆. All rights reserved.
//
import UIKit
public enum YQRefreshState {
case `default`
case pulling
case refreshing
case noMore
}
var YQKVOContentOffset = "contentOffset"
var YQKVOContentSize = "contentSize"
public let YQRefresherHeight: CGFloat = 60.0
let YQRefresherAnimationDuration = 0.25
let YQNotificatonHeaderRefresh = "YQNotificatonHeaderRefresh"
public typealias YQRefreshAction = () -> Void
public protocol Refresher where Self: UIView {
var state: YQRefreshState {get set}
var scrollView: UIScrollView? {get set}
var pullingPercent: Double {get set}
var refresherHeight: CGFloat {get}
/// 如果以开始拖动为百分比计算开始可能会看不到完整动画,所以添加一个偏移量,默认是Refresher高度的一半
var pullingPercentOffset: CGFloat {get set}
var actor: YQRefreshActor? {get set}
var action: YQRefreshAction? {get set}
var originalInset: UIEdgeInsets {get set}
var yOffset: CGFloat {get set}
func beginRefreshing()
func endRefreshing()
}
public protocol FooterRefresher: Refresher {
func noMore()
func reset()
var automaticVisiable: Bool {get set}
var topSpaceConstraint: NSLayoutConstraint! { get set}
/// 此高度及以下都当做依附的ScrollView没有内容
var emptyContentHeight: CGFloat {get set}
}
public protocol YQRefreshActor where Self: UIView {
var state: YQRefreshState {get set}
var pullingPrecent: Double {get set}
}
protocol YQRefreshable {
var header: Refresher? {get set}
var footer: FooterRefresher? {get set}
}
public struct YQRefreshContainer: YQRefreshable {
let base:UIScrollView
let headerTag = 1008601
let footerTag = 1008602
init(_ base: UIScrollView) {
self.base = base
}
public var header: Refresher? {
get {
return base.viewWithTag(headerTag) as? Refresher
}
set {
if let refresher = base.viewWithTag(headerTag) {
refresher.removeFromSuperview()
}
if let refresher = newValue {
refresher.tag = headerTag
refresher.translatesAutoresizingMaskIntoConstraints = false
refresher.originalInset = base.contentInset
base.addSubview(refresher)
refresher.addConstraint(NSLayoutConstraint(item: refresher, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: YQRefresherHeight))
base.addConstraint(NSLayoutConstraint(item: refresher, attribute: .width, relatedBy: .equal, toItem: base, attribute: .width, multiplier: 1, constant: 0))
base.addConstraint(NSLayoutConstraint(item: base, attribute: .leading, relatedBy: .equal, toItem: refresher, attribute: .leading, multiplier: 1, constant: 0))
base.addConstraint(NSLayoutConstraint(item: refresher, attribute: .bottom, relatedBy: .equal, toItem: base, attribute: .top, multiplier: 1, constant: -refresher.originalInset.top + refresher.yOffset))
base.superview?.setNeedsLayout()
base.superview?.layoutIfNeeded()
}
}
}
public var footer: FooterRefresher? {
get {
return base.viewWithTag(footerTag) as? FooterRefresher
}
set {
if let refresher = base.viewWithTag(footerTag) {
refresher.removeFromSuperview()
}
if let refresher = newValue {
refresher.tag = footerTag
refresher.originalInset = base.contentInset
refresher.translatesAutoresizingMaskIntoConstraints = false
base.addSubview(refresher)
refresher.addConstraint(NSLayoutConstraint(item: refresher, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: YQRefresherHeight))
base.addConstraint(NSLayoutConstraint(item: refresher, attribute: .width, relatedBy: .equal, toItem: base, attribute: .width, multiplier: 1, constant: 0))
base.addConstraint(NSLayoutConstraint(item: base, attribute: .leading, relatedBy: .equal, toItem: refresher, attribute: .leading, multiplier: 1, constant: 0))
refresher.topSpaceConstraint = NSLayoutConstraint(item: refresher, attribute: .top, relatedBy: .equal, toItem: base, attribute: .top, multiplier: 1, constant: 10000)
base.addConstraint(refresher.topSpaceConstraint)
}
}
}
}
public class YQRefreshActorProvider {
public static let shared = YQRefreshActorProvider()
private init() {}
public var headerActor: (() -> YQRefreshActor)?
public var footerActor: (() -> YQRefreshActor)?
}
public extension UIScrollView {
var yq: YQRefreshContainer {
get {
return YQRefreshContainer(self)
}
set {
//nothing
}
}
}
|
mit
|
8979073baf4825323c45139c04ab1e5d
| 35.595588 | 216 | 0.663452 | 4.512239 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne
|
DataPicker/DataPicker/MainViewController.swift
|
1
|
3670
|
//
// MainViewController.swift
// DataPicker
//
// Created by bingoogol on 14/9/14.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class MainViewController: UIViewController,UITextFieldDelegate {
weak var datePicker:UIDatePicker!
weak var segment:UISegmentedControl!
weak var dateText:UITextField!
override func loadView() {
self.view = UIView(frame: UIScreen.mainScreen().applicationFrame)
// 创建UIDatePicker
var datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.locale = NSLocale(localeIdentifier: "zh_Hans")
datePicker.addTarget(self, action: Selector("dateValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(datePicker)
self.datePicker = datePicker
// 创建选项卡控件
var segment = UISegmentedControl(items: ["日期","日期和时间","时间","倒计时"])
segment.frame = CGRectMake(20, 250, 280, 44)
segment.addTarget(self, action: Selector("segmentValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(segment)
self.segment = segment
// 创建文本框
var dateText = UITextField(frame: CGRectMake(20, 320, 280, 44))
// 文本控件默认没有边框
dateText.borderStyle = UITextBorderStyle.RoundedRect
// 文本控件在ios8中默认已经垂直居中了
dateText.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
dateText.delegate = self
self.view.addSubview(dateText)
self.dateText = dateText
}
override func viewDidLoad() {
segment.selectedSegmentIndex = 0
segmentValueChanged(segment)
}
func dateFromString(str:NSString) -> NSDate {
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return formatter.dateFromString(str)!
}
func segmentValueChanged(segment:UISegmentedControl) {
println(segment.selectedSegmentIndex)
switch(segment.selectedSegmentIndex) {
case 0:
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.date = dateFromString("1990-01-01 12:30");
case 1:
datePicker.datePickerMode = UIDatePickerMode.DateAndTime
datePicker.date = dateFromString("2012-12-30 10:50");
case 2:
datePicker.datePickerMode = UIDatePickerMode.Time
datePicker.date = dateFromString("2013-09-10 15:23");
case 3:
// 注意:先设置日期选择模式,再设置计时时长
datePicker.datePickerMode = UIDatePickerMode.CountDownTimer
datePicker.countDownDuration = 10 * 60
default:
break
}
dateValueChanged(datePicker)
}
func dateValueChanged(datePicker:UIDatePicker) {
var formatter = NSDateFormatter()
switch datePicker.datePickerMode {
case UIDatePickerMode.Date:
formatter.dateFormat = "yyyy-MM-dd"
case UIDatePickerMode.DateAndTime:
formatter.dateFormat = "yyyy-MM-dd HH:mm"
case UIDatePickerMode.Time:
formatter.dateFormat = "HH:mm"
case UIDatePickerMode.CountDownTimer:
formatter.dateFormat = "HH:mm:ss"
default:
break
}
dateText.text = formatter.stringFromDate(datePicker.date)
}
// 文本框代理方法,禁止用户输入
func textFieldDidBeginEditing(textField: UITextField) -> Bool {
return false
}
}
|
apache-2.0
|
3b55eb55a27b1cad2cd0149f822365c7
| 35.072165 | 121 | 0.65323 | 5.084302 | false | false | false | false |
wj2061/ios7ptl-swift3.0
|
ch08-Animation/Actions/Actions/CircleLayer.swift
|
1
|
1679
|
//
// CircleLayer.swift
// Actions
//
// Created by wj on 15/10/10.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class CircleLayer: CALayer {
var radius:CGFloat = 0{ didSet{setNeedsDisplay()} }
//This is the designated initializer for layer objects that are not in the presentation layer.
override init() {
super.init()
setNeedsDisplay()
}
//This method is the designated initializer for layer objects in the presentation layer.
override init(layer: Any) {
super.init()
setNeedsDisplay()
}
//init method required by NSCoding
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setNeedsDisplay()
}
override func draw(in ctx: CGContext) {
ctx.setFillColor(UIColor.red.cgColor)
let rect = CGRect(x: (bounds.size.width-radius)/2,
y: (bounds.size.height-radius)/2,
width: radius,
height: radius)
ctx.addEllipse(in: rect)
ctx.fillPath()
}
override class func needsDisplay(forKey key: String) -> Bool{
if key == "radius"{return true}
return super.needsDisplay(forKey: key)
}
override func action(forKey event: String) -> CAAction? {
if let layer = presentation() {
print(event)
if event == "radius"{
print("11")
let anim = CABasicAnimation(keyPath: "radius")
anim.fromValue = layer.value(forKey: "radius")
return anim
}
}
return super.action(forKey: event)
}
}
|
mit
|
f4eb932f57ef90d03b558de768220d8c
| 26.933333 | 98 | 0.569212 | 4.505376 | false | false | false | false |
jimmyhuang1114/SwiftInPractice
|
DemoTypeCasting/DemoTypeCasting/main.swift
|
1
|
3207
|
//
// main.swift
// DemoTypeCasting
//
// Created by Jimmy Huang on 12/4/14.
// Copyright (c) 2014 Jimmy Huang. All rights reserved.
//
import Foundation
/* Example 1: for using "is" to check the subclass */
let bookshelf:[AnyObject] = [
Novel(author: "九把刀", title: "那些年,我們一起追的女孩"),
Novel(author: "彎彎", title: "可不可以不要上班"),
Novel(author: "H.H先生", title: "美美的逆襲"),
Magazine(month: 12, title: "PC Home"),
Magazine(month: 1, title: "PC DIY"),
Movie(title: "Interstellar", genre: "scifi")
]
// use is to check its instance's class type
var bookCount = 0
var novelCount = 0
var magazineCount = 0
var movieCount = 0
for item in bookshelf {
if item is Novel {
novelCount++
}
if item is Magazine {
magazineCount++
}
if item is Book {
bookCount++
}
if item is Movie {
movieCount++
}
}
println("Novels:\(novelCount) Magazines:\(magazineCount) Books:\(bookCount) Movies:\(movieCount)")
println()
/* Example 2: Downcasting with as? */
let onlyBooksInshelf = [
Novel(author: "九把刀", title: "那些年,我們一起追的女孩"),
Novel(author: "彎彎", title: "可不可以不要上班"),
Novel(author: "H.H先生", title: "美美的逆襲"),
Magazine(month: 12, title: "PC Home"),
Magazine(month: 1, title: "PC DIY")
]
// print out the details by using as?
for item in onlyBooksInshelf {
if let novel = item as? Novel {
println("Novel's title: \(novel.title), author:\(novel.author)")
}else if let magazine = item as? Magazine {
println("Magazine's title: \(magazine.title), month:\(magazine.month)")
}else {
println("nothing")
}
}
println()
/* Example 3: Downcasting with as */
// we need to make sure there is no return with nil
let onlyNovelsInshelf = [
Novel(author: "九把刀", title: "那些年,我們一起追的女孩"),
Novel(author: "彎彎", title: "可不可以不要上班"),
Novel(author: "H.H先生", title: "美美的逆襲")
]
for item in onlyNovelsInshelf {
let novel = item as Novel
println("Novel's title: \(novel.title), author:\(novel.author)")
}
println()
// for shorten form of this loop
for novel in onlyNovelsInshelf as [Novel] {
println("Novel's title: \(novel.title), author:\(novel.author)")
}
println()
/* Example 4: Any type */
let shelf:[Any] = [
"iPhone 6 Plus",
1,
1.0,
Novel(author: "九把刀", title: "那些年,我們一起追的女孩"),
Movie(title: "Interstellar", genre: "Scifi")
]
// using switch to print out details
for item in shelf {
switch item {
case let anString as String:
println("\(item) is a String")
case let anInt as Int:
println("\(item) is an Int")
case let anDouble as Double:
println("\(item) is a Double")
case let aNovel as Novel:
println("\(item) is a Novel and its title & author :\(aNovel.title); \(aNovel.author)")
case let aMovie as Movie:
println("\(item) is a Movie and its title & genre:\(aMovie.title); \(aMovie.genre)")
default:
break
}
}
println()
|
apache-2.0
|
93132421495f7985be0c1a1cede306bc
| 23.883333 | 98 | 0.615075 | 3.033537 | false | false | false | false |
kstaring/swift
|
validation-test/compiler_crashers_fixed/02016-swift-tuplepattern-create.swift
|
11
|
594
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func b<S {
enum A {
func b.init() {
typealias B<d {
struct A.Element == a: (() -> {
map(g.C(T>? = "[c, g == T>() {}
}
let d, U) {
b.endIndex - range.join(.A> T where Optional<d) {
}
}
let a {
func a(t:
|
apache-2.0
|
b02a96efd8bea504439606091729daa7
| 27.285714 | 78 | 0.671717 | 3.109948 | false | false | false | false |
skyfe79/TIL
|
about.iOS/about.Swift/20.NestedType.playground/Contents.swift
|
1
|
1623
|
/*:
# Nested Types
*/
import UIKit
/*:
## Nested Type in Action
*/
do {
struct BlackjackCard {
// nested Suit enumeration
enum Suit: Character {
case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣"
}
// nested Rank enumeration
enum Rank: Int {
case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King, Ace
struct Values {
let first: Int, second: Int?
}
var values: Values {
switch self {
case .Ace:
return Values(first: 1, second: 11)
case .Jack, .Queen, .King:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil)
}
}
}
// BlackjackCard properties and methods
let rank: Rank, suit: Suit
var description: String {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}
let theAceOfSpades = BlackjackCard(rank: .Ace, suit: .Spades)
print("theAceOfSpades: \(theAceOfSpades.description)")
// Prints "theAceOfSpades: suit is ♠, value is 1 or 11"
// Referring to Nested Types
let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue
// heartsSymbol is "♡"
}
|
mit
|
b2a492f49af300c305242ae6602d8062
| 27.785714 | 73 | 0.49162 | 4.616046 | false | false | false | false |
dpereira411/GCTabView
|
GCTabView-swift/StyleKit.swift
|
1
|
25724
|
//
// StyleKit.swift
// BetexIcons
//
// Created by Daniel Pereira on 17/11/14.
// Copyright (c) 2014 Betex. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import Cocoa
public class StyleKit : NSObject {
//// Cache
private struct Cache {
static var imageOfSearchRegular: NSImage?
static var imageOfSearchBold: NSImage?
static var imageOfSearchTinted: NSImage?
static var imageOfListRegular: NSImage?
static var imageOfListTinted: NSImage?
static var imageOfFavoritesRegular: NSImage?
static var imageOfStarTinted: NSImage?
static var imageOfChronoRegular: NSImage?
static var imageOfChronoTinted: NSImage?
static var imageOfListBold: NSImage?
static var imageOfChronoBold: NSImage?
static var imageOfStarBold: NSImage?
}
//// Drawing Methods
public class func drawSearchRegular() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Oval 2 Drawing
let oval2Path = NSBezierPath(ovalInRect: NSMakeRect(15.5, 10.5, 9, 9))
color2.setStroke()
oval2Path.lineWidth = 1.1
oval2Path.stroke()
//// Bezier 4 Drawing
var bezier4Path = NSBezierPath()
bezier4Path.moveToPoint(NSMakePoint(23, 12))
bezier4Path.lineToPoint(NSMakePoint(27, 8))
color2.setStroke()
bezier4Path.lineWidth = 1.1
bezier4Path.stroke()
}
public class func drawSearchBold() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Bezier Drawing
var bezierPath = NSBezierPath()
bezierPath.moveToPoint(NSMakePoint(23, 12))
bezierPath.lineToPoint(NSMakePoint(28, 7))
color2.setStroke()
bezierPath.lineWidth = 2.5
bezierPath.stroke()
//// Oval Drawing
let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(15, 10, 10, 10))
color2.setStroke()
ovalPath.lineWidth = 2.2
ovalPath.stroke()
}
public class func drawSearchTinted() {
//// Color Declarations
let selected = NSColor(calibratedRed: 0.09, green: 0.404, blue: 0.969, alpha: 1)
//// Oval Drawing
let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(15, 10, 10, 10))
selected.setStroke()
ovalPath.lineWidth = 2.2
ovalPath.stroke()
//// Bezier Drawing
var bezierPath = NSBezierPath()
bezierPath.moveToPoint(NSMakePoint(23, 12))
bezierPath.lineToPoint(NSMakePoint(28, 7))
selected.setStroke()
bezierPath.lineWidth = 2.5
bezierPath.stroke()
}
public class func drawListRegular() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Bezier 3 Drawing
var bezier3Path = NSBezierPath()
bezier3Path.moveToPoint(NSMakePoint(24, 19.5))
bezier3Path.lineToPoint(NSMakePoint(16.86, 19.5))
bezier3Path.curveToPoint(NSMakePoint(15.5, 18), controlPoint1: NSMakePoint(15.95, 19.5), controlPoint2: NSMakePoint(15.5, 19))
bezier3Path.lineToPoint(NSMakePoint(15.5, 9))
bezier3Path.curveToPoint(NSMakePoint(16.93, 7.5), controlPoint1: NSMakePoint(15.5, 8), controlPoint2: NSMakePoint(15.95, 7.5))
bezier3Path.lineToPoint(NSMakePoint(24, 7.5))
bezier3Path.curveToPoint(NSMakePoint(25.5, 9), controlPoint1: NSMakePoint(25, 7.5), controlPoint2: NSMakePoint(25.5, 8))
bezier3Path.lineToPoint(NSMakePoint(25.5, 18))
bezier3Path.curveToPoint(NSMakePoint(24, 19.5), controlPoint1: NSMakePoint(25.5, 19), controlPoint2: NSMakePoint(25, 19.5))
bezier3Path.closePath()
bezier3Path.miterLimit = 4
bezier3Path.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
color2.setStroke()
bezier3Path.lineWidth = 1.1
bezier3Path.stroke()
//// Bezier Drawing
var bezierPath = NSBezierPath()
bezierPath.moveToPoint(NSMakePoint(17.5, 21))
bezierPath.curveToPoint(NSMakePoint(17.5, 19.5), controlPoint1: NSMakePoint(17.5, 19.5), controlPoint2: NSMakePoint(17.5, 19.5))
bezierPath.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
color2.setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
//// Bezier 2 Drawing
var bezier2Path = NSBezierPath()
bezier2Path.moveToPoint(NSMakePoint(23.5, 21))
bezier2Path.curveToPoint(NSMakePoint(23.5, 19.5), controlPoint1: NSMakePoint(23.5, 19.5), controlPoint2: NSMakePoint(23.5, 19.5))
bezier2Path.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
color2.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
//// Bezier 5 Drawing
var bezier5Path = NSBezierPath()
bezier5Path.moveToPoint(NSMakePoint(20.5, 21))
bezier5Path.curveToPoint(NSMakePoint(20.5, 19.5), controlPoint1: NSMakePoint(20.5, 19.5), controlPoint2: NSMakePoint(20.5, 19.5))
bezier5Path.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
color2.setStroke()
bezier5Path.lineWidth = 1
bezier5Path.stroke()
//// Bezier 6 Drawing
var bezier6Path = NSBezierPath()
bezier6Path.moveToPoint(NSMakePoint(18, 16.5))
bezier6Path.curveToPoint(NSMakePoint(23, 16.5), controlPoint1: NSMakePoint(23.46, 16.5), controlPoint2: NSMakePoint(23, 16.5))
color2.setStroke()
bezier6Path.lineWidth = 1
bezier6Path.stroke()
//// Bezier 7 Drawing
var bezier7Path = NSBezierPath()
bezier7Path.moveToPoint(NSMakePoint(18, 13.5))
bezier7Path.curveToPoint(NSMakePoint(23, 13.5), controlPoint1: NSMakePoint(23.46, 13.5), controlPoint2: NSMakePoint(23, 13.5))
color2.setStroke()
bezier7Path.lineWidth = 1
bezier7Path.stroke()
//// Bezier 8 Drawing
var bezier8Path = NSBezierPath()
bezier8Path.moveToPoint(NSMakePoint(18, 10.5))
bezier8Path.curveToPoint(NSMakePoint(23, 10.5), controlPoint1: NSMakePoint(23.46, 10.5), controlPoint2: NSMakePoint(23, 10.5))
color2.setStroke()
bezier8Path.lineWidth = 1
bezier8Path.stroke()
}
public class func drawListTinted() {
//// Color Declarations
let selected = NSColor(calibratedRed: 0.09, green: 0.404, blue: 0.969, alpha: 1)
//// Bezier 3 Drawing
var bezier3Path = NSBezierPath()
bezier3Path.moveToPoint(NSMakePoint(24, 20))
bezier3Path.lineToPoint(NSMakePoint(17, 20))
bezier3Path.curveToPoint(NSMakePoint(15, 18), controlPoint1: NSMakePoint(15.5, 20), controlPoint2: NSMakePoint(15, 19.5))
bezier3Path.lineToPoint(NSMakePoint(15, 9))
bezier3Path.curveToPoint(NSMakePoint(17, 7), controlPoint1: NSMakePoint(15, 7.5), controlPoint2: NSMakePoint(15.5, 7))
bezier3Path.lineToPoint(NSMakePoint(24, 7))
bezier3Path.curveToPoint(NSMakePoint(26, 9), controlPoint1: NSMakePoint(25.5, 7), controlPoint2: NSMakePoint(26, 7.5))
bezier3Path.lineToPoint(NSMakePoint(26, 18))
bezier3Path.curveToPoint(NSMakePoint(24, 20), controlPoint1: NSMakePoint(26, 19.5), controlPoint2: NSMakePoint(25.5, 20))
bezier3Path.closePath()
bezier3Path.miterLimit = 4
bezier3Path.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
selected.setStroke()
bezier3Path.lineWidth = 2
bezier3Path.stroke()
//// Bezier Drawing
var bezierPath = NSBezierPath()
bezierPath.moveToPoint(NSMakePoint(17.5, 22))
bezierPath.curveToPoint(NSMakePoint(17.5, 20.5), controlPoint1: NSMakePoint(17.5, 20.5), controlPoint2: NSMakePoint(17.5, 20.5))
bezierPath.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
selected.setStroke()
bezierPath.lineWidth = 2
bezierPath.stroke()
//// Bezier 4 Drawing
var bezier4Path = NSBezierPath()
bezier4Path.moveToPoint(NSMakePoint(23.5, 22))
bezier4Path.curveToPoint(NSMakePoint(23.5, 20.5), controlPoint1: NSMakePoint(23.5, 20.5), controlPoint2: NSMakePoint(23.5, 20.5))
bezier4Path.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
selected.setStroke()
bezier4Path.lineWidth = 2
bezier4Path.stroke()
//// Bezier 5 Drawing
var bezier5Path = NSBezierPath()
bezier5Path.moveToPoint(NSMakePoint(20.5, 22))
bezier5Path.curveToPoint(NSMakePoint(20.5, 20.5), controlPoint1: NSMakePoint(20.5, 20.5), controlPoint2: NSMakePoint(20.5, 20.5))
bezier5Path.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
selected.setStroke()
bezier5Path.lineWidth = 2
bezier5Path.stroke()
//// Bezier 6 Drawing
var bezier6Path = NSBezierPath()
bezier6Path.moveToPoint(NSMakePoint(18, 16.5))
bezier6Path.curveToPoint(NSMakePoint(23, 16.5), controlPoint1: NSMakePoint(23.46, 16.5), controlPoint2: NSMakePoint(23, 16.5))
selected.setStroke()
bezier6Path.lineWidth = 1
bezier6Path.stroke()
//// Bezier 7 Drawing
var bezier7Path = NSBezierPath()
bezier7Path.moveToPoint(NSMakePoint(18, 13.5))
bezier7Path.curveToPoint(NSMakePoint(23, 13.5), controlPoint1: NSMakePoint(23.46, 13.5), controlPoint2: NSMakePoint(23, 13.5))
selected.setStroke()
bezier7Path.lineWidth = 1
bezier7Path.stroke()
//// Bezier 8 Drawing
var bezier8Path = NSBezierPath()
bezier8Path.moveToPoint(NSMakePoint(18, 10.5))
bezier8Path.curveToPoint(NSMakePoint(23, 10.5), controlPoint1: NSMakePoint(23.46, 10.5), controlPoint2: NSMakePoint(23, 10.5))
selected.setStroke()
bezier8Path.lineWidth = 1
bezier8Path.stroke()
}
public class func drawFavoritesRegular() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Bezier 4 Drawing
var bezier4Path = NSBezierPath()
bezier4Path.moveToPoint(NSMakePoint(20.52, 20.81))
bezier4Path.lineToPoint(NSMakePoint(22.14, 16.23))
bezier4Path.lineToPoint(NSMakePoint(24.61, 16.18))
bezier4Path.lineToPoint(NSMakePoint(25.77, 16.15))
bezier4Path.lineToPoint(NSMakePoint(27.13, 16.13))
bezier4Path.lineToPoint(NSMakePoint(23.16, 13.19))
bezier4Path.lineToPoint(NSMakePoint(24.59, 8.5))
bezier4Path.lineToPoint(NSMakePoint(20.52, 11.29))
bezier4Path.lineToPoint(NSMakePoint(16.44, 8.5))
bezier4Path.lineToPoint(NSMakePoint(17.87, 13.19))
bezier4Path.lineToPoint(NSMakePoint(13.9, 16.13))
bezier4Path.lineToPoint(NSMakePoint(18.89, 16.23))
bezier4Path.lineToPoint(NSMakePoint(20.52, 20.81))
bezier4Path.closePath()
bezier4Path.miterLimit = 4
bezier4Path.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
color2.setStroke()
bezier4Path.lineWidth = 1.1
bezier4Path.stroke()
}
public class func drawStarTinted() {
//// Color Declarations
let selected = NSColor(calibratedRed: 0.09, green: 0.404, blue: 0.969, alpha: 1)
//// Bezier Drawing
var bezierPath = NSBezierPath()
bezierPath.moveToPoint(NSMakePoint(20.55, 22.31))
bezierPath.lineToPoint(NSMakePoint(22.53, 16.8))
bezierPath.lineToPoint(NSMakePoint(28.6, 16.68))
bezierPath.lineToPoint(NSMakePoint(23.77, 13.14))
bezierPath.lineToPoint(NSMakePoint(25.5, 7.5))
bezierPath.lineToPoint(NSMakePoint(20.55, 10.86))
bezierPath.lineToPoint(NSMakePoint(15.6, 7.5))
bezierPath.lineToPoint(NSMakePoint(17.33, 13.14))
bezierPath.lineToPoint(NSMakePoint(12.5, 16.68))
bezierPath.lineToPoint(NSMakePoint(18.57, 16.8))
bezierPath.lineToPoint(NSMakePoint(20.55, 22.31))
bezierPath.closePath()
bezierPath.miterLimit = 4
bezierPath.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
selected.setStroke()
bezierPath.lineWidth = 2
bezierPath.stroke()
}
public class func drawChronoRegular() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Oval Drawing
let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(14.5, 7.5, 12, 12))
color2.setStroke()
ovalPath.lineWidth = 1.1
ovalPath.stroke()
//// Bezier 2 Drawing
var bezier2Path = NSBezierPath()
bezier2Path.moveToPoint(NSMakePoint(20.5, 15.5))
bezier2Path.lineToPoint(NSMakePoint(20.5, 13))
bezier2Path.lineToPoint(NSMakePoint(20.5, 15.5))
bezier2Path.closePath()
bezier2Path.miterLimit = 4
bezier2Path.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
color2.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
//// Bezier 9 Drawing
var bezier9Path = NSBezierPath()
bezier9Path.moveToPoint(NSMakePoint(20.5, 19.5))
bezier9Path.lineToPoint(NSMakePoint(20.5, 21.5))
color2.setStroke()
bezier9Path.lineWidth = 1.1
bezier9Path.stroke()
//// Bezier 10 Drawing
var bezier10Path = NSBezierPath()
bezier10Path.moveToPoint(NSMakePoint(24.5, 17.5))
bezier10Path.lineToPoint(NSMakePoint(26.5, 19.5))
color2.setStroke()
bezier10Path.lineWidth = 1.1
bezier10Path.stroke()
}
public class func drawChronoTinted() {
//// Color Declarations
let selected = NSColor(calibratedRed: 0.09, green: 0.404, blue: 0.969, alpha: 1)
//// Oval Drawing
let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(14, 7, 13, 13))
selected.setStroke()
ovalPath.lineWidth = 2.2
ovalPath.stroke()
//// Bezier 2 Drawing
var bezier2Path = NSBezierPath()
bezier2Path.moveToPoint(NSMakePoint(20.5, 15.5))
bezier2Path.lineToPoint(NSMakePoint(20.5, 13))
bezier2Path.lineToPoint(NSMakePoint(20.5, 15.5))
bezier2Path.closePath()
bezier2Path.miterLimit = 4
bezier2Path.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
selected.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
//// Bezier 9 Drawing
var bezier9Path = NSBezierPath()
bezier9Path.moveToPoint(NSMakePoint(20.5, 20.5))
bezier9Path.lineToPoint(NSMakePoint(20.5, 23))
selected.setStroke()
bezier9Path.lineWidth = 2
bezier9Path.stroke()
//// Bezier 10 Drawing
var bezier10Path = NSBezierPath()
bezier10Path.moveToPoint(NSMakePoint(25, 18))
bezier10Path.lineToPoint(NSMakePoint(28, 21))
selected.setStroke()
bezier10Path.lineWidth = 2
bezier10Path.stroke()
}
public class func drawListBold() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Bezier 3 Drawing
var bezier3Path = NSBezierPath()
bezier3Path.moveToPoint(NSMakePoint(24, 20))
bezier3Path.lineToPoint(NSMakePoint(17, 20))
bezier3Path.curveToPoint(NSMakePoint(15, 18), controlPoint1: NSMakePoint(15.5, 20), controlPoint2: NSMakePoint(15, 19.5))
bezier3Path.lineToPoint(NSMakePoint(15, 9))
bezier3Path.curveToPoint(NSMakePoint(17, 7), controlPoint1: NSMakePoint(15, 7.5), controlPoint2: NSMakePoint(15.5, 7))
bezier3Path.lineToPoint(NSMakePoint(24, 7))
bezier3Path.curveToPoint(NSMakePoint(26, 9), controlPoint1: NSMakePoint(25.5, 7), controlPoint2: NSMakePoint(26, 7.5))
bezier3Path.lineToPoint(NSMakePoint(26, 18))
bezier3Path.curveToPoint(NSMakePoint(24, 20), controlPoint1: NSMakePoint(26, 19.5), controlPoint2: NSMakePoint(25.5, 20))
bezier3Path.closePath()
bezier3Path.miterLimit = 4
bezier3Path.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
color2.setStroke()
bezier3Path.lineWidth = 2
bezier3Path.stroke()
//// Bezier Drawing
var bezierPath = NSBezierPath()
bezierPath.moveToPoint(NSMakePoint(17.5, 22))
bezierPath.curveToPoint(NSMakePoint(17.5, 20.5), controlPoint1: NSMakePoint(17.5, 20.5), controlPoint2: NSMakePoint(17.5, 20.5))
bezierPath.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
color2.setStroke()
bezierPath.lineWidth = 2
bezierPath.stroke()
//// Bezier 4 Drawing
var bezier4Path = NSBezierPath()
bezier4Path.moveToPoint(NSMakePoint(23.5, 22))
bezier4Path.curveToPoint(NSMakePoint(23.5, 20.5), controlPoint1: NSMakePoint(23.5, 20.5), controlPoint2: NSMakePoint(23.5, 20.5))
bezier4Path.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
color2.setStroke()
bezier4Path.lineWidth = 2
bezier4Path.stroke()
//// Bezier 5 Drawing
var bezier5Path = NSBezierPath()
bezier5Path.moveToPoint(NSMakePoint(20.5, 22))
bezier5Path.curveToPoint(NSMakePoint(20.5, 20.5), controlPoint1: NSMakePoint(20.5, 20.5), controlPoint2: NSMakePoint(20.5, 20.5))
bezier5Path.lineCapStyle = NSLineCapStyle.RoundLineCapStyle
color2.setStroke()
bezier5Path.lineWidth = 2
bezier5Path.stroke()
//// Bezier 6 Drawing
var bezier6Path = NSBezierPath()
bezier6Path.moveToPoint(NSMakePoint(18, 16.5))
bezier6Path.curveToPoint(NSMakePoint(23, 16.5), controlPoint1: NSMakePoint(23.46, 16.5), controlPoint2: NSMakePoint(23, 16.5))
color2.setStroke()
bezier6Path.lineWidth = 1
bezier6Path.stroke()
//// Bezier 7 Drawing
var bezier7Path = NSBezierPath()
bezier7Path.moveToPoint(NSMakePoint(18, 13.5))
bezier7Path.curveToPoint(NSMakePoint(23, 13.5), controlPoint1: NSMakePoint(23.46, 13.5), controlPoint2: NSMakePoint(23, 13.5))
color2.setStroke()
bezier7Path.lineWidth = 1
bezier7Path.stroke()
//// Bezier 8 Drawing
var bezier8Path = NSBezierPath()
bezier8Path.moveToPoint(NSMakePoint(18, 10.5))
bezier8Path.curveToPoint(NSMakePoint(23, 10.5), controlPoint1: NSMakePoint(23.46, 10.5), controlPoint2: NSMakePoint(23, 10.5))
color2.setStroke()
bezier8Path.lineWidth = 1
bezier8Path.stroke()
}
public class func drawChronoBold() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Oval Drawing
let ovalPath = NSBezierPath(ovalInRect: NSMakeRect(14, 7, 13, 13))
color2.setStroke()
ovalPath.lineWidth = 2.2
ovalPath.stroke()
//// Bezier 2 Drawing
var bezier2Path = NSBezierPath()
bezier2Path.moveToPoint(NSMakePoint(20.5, 15.5))
bezier2Path.lineToPoint(NSMakePoint(20.5, 13))
bezier2Path.lineToPoint(NSMakePoint(20.5, 15.5))
bezier2Path.closePath()
bezier2Path.miterLimit = 4
bezier2Path.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
color2.setStroke()
bezier2Path.lineWidth = 1
bezier2Path.stroke()
//// Bezier 9 Drawing
var bezier9Path = NSBezierPath()
bezier9Path.moveToPoint(NSMakePoint(20.5, 20.5))
bezier9Path.lineToPoint(NSMakePoint(20.5, 23))
color2.setStroke()
bezier9Path.lineWidth = 2
bezier9Path.stroke()
//// Bezier 10 Drawing
var bezier10Path = NSBezierPath()
bezier10Path.moveToPoint(NSMakePoint(25, 18))
bezier10Path.lineToPoint(NSMakePoint(28, 21))
color2.setStroke()
bezier10Path.lineWidth = 2
bezier10Path.stroke()
}
public class func drawStarBold() {
//// Color Declarations
let color2 = NSColor(calibratedRed: 0.236, green: 0.236, blue: 0.236, alpha: 1)
//// Bezier Drawing
var bezierPath = NSBezierPath()
bezierPath.moveToPoint(NSMakePoint(20.55, 22.31))
bezierPath.lineToPoint(NSMakePoint(22.53, 16.8))
bezierPath.lineToPoint(NSMakePoint(28.6, 16.68))
bezierPath.lineToPoint(NSMakePoint(23.77, 13.14))
bezierPath.lineToPoint(NSMakePoint(25.5, 7.5))
bezierPath.lineToPoint(NSMakePoint(20.55, 10.86))
bezierPath.lineToPoint(NSMakePoint(15.6, 7.5))
bezierPath.lineToPoint(NSMakePoint(17.33, 13.14))
bezierPath.lineToPoint(NSMakePoint(12.5, 16.68))
bezierPath.lineToPoint(NSMakePoint(18.57, 16.8))
bezierPath.lineToPoint(NSMakePoint(20.55, 22.31))
bezierPath.closePath()
bezierPath.miterLimit = 4
bezierPath.lineJoinStyle = NSLineJoinStyle.RoundLineJoinStyle
color2.setStroke()
bezierPath.lineWidth = 2
bezierPath.stroke()
}
//// Generated Images
public class var imageOfSearchRegular: NSImage {
if Cache.imageOfSearchRegular != nil {
return Cache.imageOfSearchRegular!
}
Cache.imageOfSearchRegular = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawSearchRegular()
return true
}
return Cache.imageOfSearchRegular!
}
public class var imageOfSearchBold: NSImage {
if Cache.imageOfSearchBold != nil {
return Cache.imageOfSearchBold!
}
Cache.imageOfSearchBold = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawSearchBold()
return true
}
return Cache.imageOfSearchBold!
}
public class var imageOfSearchTinted: NSImage {
if Cache.imageOfSearchTinted != nil {
return Cache.imageOfSearchTinted!
}
Cache.imageOfSearchTinted = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawSearchTinted()
return true
}
return Cache.imageOfSearchTinted!
}
public class var imageOfListRegular: NSImage {
if Cache.imageOfListRegular != nil {
return Cache.imageOfListRegular!
}
Cache.imageOfListRegular = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawListRegular()
return true
}
return Cache.imageOfListRegular!
}
public class var imageOfListTinted: NSImage {
if Cache.imageOfListTinted != nil {
return Cache.imageOfListTinted!
}
Cache.imageOfListTinted = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawListTinted()
return true
}
return Cache.imageOfListTinted!
}
public class var imageOfFavoritesRegular: NSImage {
if Cache.imageOfFavoritesRegular != nil {
return Cache.imageOfFavoritesRegular!
}
Cache.imageOfFavoritesRegular = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawFavoritesRegular()
return true
}
return Cache.imageOfFavoritesRegular!
}
public class var imageOfStarTinted: NSImage {
if Cache.imageOfStarTinted != nil {
return Cache.imageOfStarTinted!
}
Cache.imageOfStarTinted = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawStarTinted()
return true
}
return Cache.imageOfStarTinted!
}
public class var imageOfChronoRegular: NSImage {
if Cache.imageOfChronoRegular != nil {
return Cache.imageOfChronoRegular!
}
Cache.imageOfChronoRegular = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawChronoRegular()
return true
}
return Cache.imageOfChronoRegular!
}
public class var imageOfChronoTinted: NSImage {
if Cache.imageOfChronoTinted != nil {
return Cache.imageOfChronoTinted!
}
Cache.imageOfChronoTinted = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawChronoTinted()
return true
}
return Cache.imageOfChronoTinted!
}
public class var imageOfListBold: NSImage {
if Cache.imageOfListBold != nil {
return Cache.imageOfListBold!
}
Cache.imageOfListBold = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawListBold()
return true
}
return Cache.imageOfListBold!
}
public class var imageOfChronoBold: NSImage {
if Cache.imageOfChronoBold != nil {
return Cache.imageOfChronoBold!
}
Cache.imageOfChronoBold = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawChronoBold()
return true
}
return Cache.imageOfChronoBold!
}
public class var imageOfStarBold: NSImage {
if Cache.imageOfStarBold != nil {
return Cache.imageOfStarBold!
}
Cache.imageOfStarBold = NSImage(size: NSMakeSize(41, 28), flipped: false) { (NSRect) -> Bool in
StyleKit.drawStarBold()
return true
}
return Cache.imageOfStarBold!
}
}
|
mit
|
3c6c155b1f2629c48cd884e0a00c5fbd
| 35.906743 | 137 | 0.645895 | 4.230225 | false | false | false | false |
groschovskiy/lerigos_music
|
Mobile/iOS/Beta/Pods/PhoneNumberKit/PhoneNumberKit/RegularExpressions.swift
|
1
|
10272
|
//
// RegularExpressions.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 04/10/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
class RegularExpressions {
static let sharedInstance = RegularExpressions()
var regularExpresions = [String:NSRegularExpression]()
var phoneDataDetector: NSDataDetector?
var spaceCharacterSet: NSCharacterSet = {
let characterSet = NSMutableCharacterSet(charactersInString: "\u{00a0}")
characterSet.formUnionWithCharacterSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return characterSet
}()
deinit {
regularExpresions.removeAll()
phoneDataDetector = nil
}
// MARK: Regular expression
func regexWithPattern(pattern: String) throws -> NSRegularExpression {
var safeRegex = regularExpresions
if let regex = safeRegex[pattern] {
return regex
}
else {
do {
let currentPattern: NSRegularExpression
currentPattern = try NSRegularExpression(pattern: pattern, options:NSRegularExpressionOptions.CaseInsensitive)
safeRegex.updateValue(currentPattern, forKey: pattern)
self.regularExpresions = safeRegex
return currentPattern
}
catch {
throw PhoneNumberError.GeneralError
}
}
}
func regexMatches(pattern: String, string: String) throws -> [NSTextCheckingResult] {
do {
let internalString = string
let currentPattern = try regexWithPattern(pattern)
// NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range.
let nsString = internalString as NSString
let stringRange = NSMakeRange(0, nsString.length)
let matches = currentPattern.matchesInString(internalString, options: [], range: stringRange)
return matches
}
catch {
throw PhoneNumberError.GeneralError
}
}
func phoneDataDetectorMatches(string: String) throws -> [NSTextCheckingResult] {
let dataDetector: NSDataDetector
if let detector = phoneDataDetector {
dataDetector = detector
}
else {
do {
dataDetector = try NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue)
self.phoneDataDetector = dataDetector
}
catch {
throw PhoneNumberError.GeneralError
}
}
let nsString = string as NSString
let stringRange = NSMakeRange(0, nsString.length)
let matches = dataDetector.matchesInString(string, options: [], range: stringRange)
if matches.isEmpty == false {
return matches
}
else {
let fallBackMatches = try regexMatches(validPhoneNumberPattern, string: string)
if fallBackMatches.isEmpty == false {
return fallBackMatches
}
else {
throw PhoneNumberError.NotANumber
}
}
}
// MARK: Match helpers
func matchesAtStart(pattern: String, string: String) -> Bool {
do {
let matches = try regexMatches(pattern, string: string)
for match in matches {
if match.range.location == 0 {
return true
}
}
}
catch {
}
return false
}
func stringPositionByRegex(pattern: String, string: String) -> Int {
do {
let matches = try regexMatches(pattern, string: string)
if let match = matches.first {
return (match.range.location)
}
return -1
} catch {
return -1
}
}
func matchesExist(pattern: String?, string: String) -> Bool {
guard let pattern = pattern else {
return false
}
do {
let matches = try regexMatches(pattern, string: string)
return matches.count > 0
}
catch {
return false
}
}
func matchesEntirely(pattern: String?, string: String) -> Bool {
guard let pattern = pattern else {
return false
}
var isMatchingEntirely: Bool = false
do {
let matches = try regexMatches(pattern, string: string)
let nsString = string as NSString
let stringRange = NSMakeRange(0, nsString.length)
for match in matches {
if (NSEqualRanges(match.range, stringRange)) {
isMatchingEntirely = true
}
}
return isMatchingEntirely
}
catch {
return false
}
}
func matchedStringByRegex(pattern: String, string: String) throws -> [String] {
do {
let matches = try regexMatches(pattern, string: string)
var matchedStrings = [String]()
for match in matches {
let processedString = string.substringWithNSRange(match.range)
matchedStrings.append(processedString)
}
return matchedStrings
}
catch {
}
return []
}
// MARK: String and replace
func replaceStringByRegex(pattern: String, string: String) -> String {
do {
var replacementResult = string
let regex = try regexWithPattern(pattern)
// NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range.
let nsString = string as NSString
let stringRange = NSMakeRange(0, nsString.length)
let matches = regex.matchesInString(string,
options: [], range: stringRange)
if matches.count == 1 {
let range = regex.rangeOfFirstMatchInString(string, options: [], range: stringRange)
if range.location != NSNotFound {
replacementResult = regex.stringByReplacingMatchesInString(string, options: [], range: range, withTemplate: "")
}
return replacementResult
}
else if matches.count > 1 {
replacementResult = regex.stringByReplacingMatchesInString(string, options: [], range: stringRange, withTemplate: "")
}
return replacementResult
} catch {
return string
}
}
func replaceStringByRegex(pattern: String, string: String, template: String) -> String {
do {
var replacementResult = string
let regex = try regexWithPattern(pattern)
// NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range.
let nsString = string as NSString
let stringRange = NSMakeRange(0, nsString.length)
let matches = regex.matchesInString(string,
options: [], range: stringRange)
if matches.count == 1 {
let range = regex.rangeOfFirstMatchInString(string, options: [], range: stringRange)
if range.location != NSNotFound {
replacementResult = regex.stringByReplacingMatchesInString(string, options: [], range: range, withTemplate: template)
}
return replacementResult
}
else if matches.count > 1 {
replacementResult = regex.stringByReplacingMatchesInString(string, options: [], range: stringRange, withTemplate: template)
}
return replacementResult
} catch {
return string
}
}
func replaceFirstStringByRegex(pattern: String, string: String, templateString: String) -> String {
do {
// NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range.
var nsString = string as NSString
let stringRange = NSMakeRange(0, nsString.length)
let regex = try regexWithPattern(pattern)
let range = regex.rangeOfFirstMatchInString(string, options: [], range: stringRange)
if range.location != NSNotFound {
nsString = regex.stringByReplacingMatchesInString(string, options: [], range: range, withTemplate: templateString)
}
return nsString as String
} catch {
return String()
}
}
func stringByReplacingOccurrences(string: String, map: [String:String], removeNonMatches: Bool) -> String {
var targetString = String()
let copiedString = string
for i in 0 ..< string.characters.count {
let oneChar = copiedString[copiedString.startIndex.advancedBy(i)]
let keyString = String(oneChar)
if let mappedValue = map[keyString.uppercaseString] {
targetString.appendContentsOf(mappedValue)
}
else if removeNonMatches == false {
targetString.appendContentsOf(keyString as String)
}
}
return targetString
}
// MARK: Validations
func hasValue(value: NSString?) -> Bool {
if let valueString = value {
if valueString.stringByTrimmingCharactersInSet(spaceCharacterSet).characters.count == 0 {
return false
}
return true
}
else {
return false
}
}
func testStringLengthAgainstPattern(pattern: String, string: String) -> Bool {
if (matchesEntirely(pattern, string: string)) {
return true
}
else {
return false
}
}
}
// MARK: Extensions
extension String {
func substringWithNSRange(range: NSRange) -> String {
let nsString = self as NSString
return nsString.substringWithRange(range)
}
}
|
apache-2.0
|
d5aa3d16782376c7f8adcb6f5a73a7c9
| 33.699324 | 142 | 0.580567 | 5.542903 | false | false | false | false |
rhx/gir2swift
|
Sources/libgir2swift/emitting/c2swift.swift
|
1
|
17002
|
//
// c2swift.swift
// gir2swift
//
// Created by Rene Hexel on 29/04/2016.
// Copyright © 2016, 2017, 2018, 2019, 2020 Rene Hexel. All rights reserved.
//
import Foundation
/// Scalar C types that have an equivalent in Swift
private let castableScalars = [ "gint" : "CInt", "glong" : "CLong", "guint" : "CUnsignedInt", "char" : "CChar",
"gint8" : "Int8", "guint8" : "UInt8", "gint16" : "Int16", "guint16" : "UInt16",
"gint32" : "Int32", "guint32" : "UInt32", "gint64" : "Int64", "guint64" : "UInt64",
"gulong" : "CUnsignedLong", "gsize" : "Int", "gboolean" : "Bool", "goffset" : "Int"]
/// C pointer types that have an equivalent in Swift
private let castablePointers = [ "gpointer" : "UnsafeMutableRawPointer" ]
/// Swift pointer types that have an equivalent in C
private let reversePointers = castablePointers.reduce(Dictionary<String,String>()) {
var dict = $0
dict[$1.1] = $1.0
return dict
}
/// Scalar Swift types that have an equivalent in C
private let reversecast = castableScalars.reduce(reversePointers) {
var dict = $0
dict[$1.1] = $1.0
return dict
}
/// Swift fundamental type names
private let swiftFundamentalsForC = [
"char" : "CChar", "unsigned char" : "CUnsignedChar",
"int" : "CInt", "unsigned int" : "CUnsignedInt", "unsigned" : "CUnsignedInt",
"long" : "CLong", "unsigned long" : "CUnsignedLong",
"long long" : "CLongLong", "unsigned long long" : "CUnsignedLongLong",
"short" : "CShort", "unsigned short" : "CUnsignedShort",
"double" : "CDouble", "float" : "CFloat", "long double" : "CLongDouble",
"void" : "Void",
"int8_t" : "Int8", "uint8_t" : "UInt8",
"int16_t" : "Int16", "uint16_t" : "UInt16",
"int32_t" : "Int32", "uint32_t" : "UInt32",
"int64_t" : "Int64", "uint64_t" : "UInt64"
]
/// Swift fundamental, scalar type name replacements
private let swiftFullTypesForC = swiftFundamentalsForC.merging([
"va_list" : "CVaListPointer",
"UnsafeMutablePointer<Void>" : "UnsafeMutableRawPointer",
"UnsafeMutablePointer<Void>!" : "UnsafeMutableRawPointer!",
"UnsafeMutablePointer<Void>?" : "UnsafeMutableRawPointer?",
"UnsafePointer<Void>" : "UnsafeRawPointer",
"UnsafePointer<Void>!" : "UnsafeRawPointer!",
"UnsafePointer<Void>?" : "UnsafeRawPointer?",
]) { $1 }
/// Swift type equivalents for C types
private let swiftReplacementsForC = swiftFullTypesForC.merging([
"utf8" : "String", "filename" : "String",
"Error" : "GLibError"
]) { $1 }
/// Mapping that allows casting from original C types to more idiomatic Swift types
/// FIXME: these types only work correctly on 64bit systems
private let swiftConvenience = [ "CInt" : "Int", "CUnsignedInt" : "Int",
"CLong" : "Int", "CUnsignedLong" : "Int", "CLongLong" : "Int", "CUnsignedLongLong" : "Int",
"CShort" : "Int", "CUnsignedShort" : "Int", "CDouble" : "Double", "CFloat" : "Double",
"gfloat" : "Float", "gdouble" : "Double" ]
/// Idiomatic Swift type equivalents for C types
private let swiftIdiomaticReplacements: [ String : String] = swiftReplacementsForC.mapValues {
guard let replacement = swiftConvenience[$0] else { return $0 }
return replacement
}
/// Verbatim Swift type equivalents for C types
private let swiftVerbatimReplacements = swiftReplacementsForC.mapValues { $0 == "String" ? "UnsafePointer<CChar>?" : $0 }
/// Verbatim Swift type equivalents for C types
private let swiftVerbatimIdiomaticReplacements = swiftIdiomaticReplacements.mapValues { $0 == "String" ? "UnsafePointer<CChar>?" : $0 }
/// Types that already exist in Swift and therefore need to be treated specially
private let reservedTypes: Set = ["String", "Array", "Optional", "Set", "Error", "ErrorProtocol"]
/// Known Swift type names
private let typeNames: Set = reservedTypes.union(reversecast.keys)
/// Swift keyword for `true` Boolean values
private let trueS = "true"
/// Swift keyword for `false` Boolean values
private let falseS = "false"
/// Swift keyword for `nil` values
private let nilS = "nil"
/// Keywords reserved for declarations in Swift
private let declarationKeywords: Set = ["associatedtype", "class", "deinit", "enum", "extension", "func", "import", "init", "inout", "internal", "let", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var"];
/// Keywords reserved for statements in Swift
private let statementKeywords: Set = ["break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch", "where", "while"]
/// Keywords reserved for expressions in Swift
private let expressionKeywords: Set = ["as", "catch", "dynamicType", "false", "is", "nil", "rethrows", "super", "self", "Self", "throw", "throws", "true", "try", "#column", "#file", "#function", "#line."]
/// Keywords with specific meanings in Swift
private let specificKeywords: Set = ["associativity", "convenience", "dynamic", "didSet", "final", "infix", "indirect", "lazy", "left", "mutating", "none", "nonmutating", "optional", "override", "postfix", "precedence", "prefix", "Protocol", "required", "right", "Type", "unowned", "weak", "willSet"]
infix operator ∪: LogicalDisjunctionPrecedence
/// Set union operator
/// - Parameters:
/// - left: lefthand side set to form a union from
/// - right: righthand side set to form a union from
@inlinable
func ∪<T>(left: Set<T>, right: Set<T>) -> Set<T> {
return left.union(right)
}
/// Set union operator
/// - Parameters:
/// - left: lefthand side set to form a union from
/// - right: set element to include in the union
@inlinable
func ∪<T>(left: Set<T>, right: T) -> Set<T> {
return left.union([right])
}
/// Set union operator
/// - Parameters:
/// - left: set element to include in the union
/// - right: righthand side set to form a union from
@inlinable
func ∪<T>(left: T, right: Set<T>) -> Set<T> {
return Set<T>(arrayLiteral: left).union(right)
}
/// List of all Swiftwords in Swift
let swiftKeywords = declarationKeywords ∪ statementKeywords ∪ expressionKeywords ∪ specificKeywords
/// List of all reserved names in Swift
let reservedNames = typeNames ∪ swiftKeywords
public extension String {
/// return a name with reserved Ref or Protocol suffixes escaped
var typeEscaped: String {
let nx: String
if let sf = [ "Protocol", "Ref" ].filter({ self.hasSuffix($0) }).first {
nx = stringByRemovingAnEquivalentNumberOfCharactersAs(suffix: sf) + "_" + sf
} else {
nx = self
}
return nx
}
/// Return a string that starts with an alpha or underscore character
var swiftIdentifier: String {
self.first?.isLetter == false && self.first != "_"
? "_" + self
: self
}
/// return a valid Swift type for an underlying C type
var validSwift: String {
if let s = swiftFundamentalsForC[self] { return s }
return swiftIdentifier
}
/// return a valid, full Swift type (including pointers) for an underlying C type
var validFullSwift: String {
if let s = swiftFullTypesForC[self] { return s }
return swiftIdentifier
}
/// return a valid Swift type for an underlying C type
var swiftType: String {
if let s = swiftReplacementsForC[self] { return s }
return swiftIdentifier
}
/// Assuming the receiver is a Swift type,
/// return an idiomatic type corresponding to the receiver
var idiomatic: String {
guard let idiomatic = swiftConvenience[self] else { return self }
return idiomatic
}
/// return a valid, idiomatic Swift type for an underlying C type
var swiftTypeIdiomatic: String {
if let s = swiftIdiomaticReplacements[self] { return s }
return swiftIdentifier
}
/// return a valid, verbatim Swift type for an underlying C type
var swiftTypeVerbatim: String {
if let s = swiftVerbatimReplacements[self] { return s }
return swiftIdentifier
}
/// return an idiomatic, verbatim Swift type for an underlying C type
var swiftTypeVerbatimIdiomatic: String {
if let s = swiftVerbatimIdiomaticReplacements[self] { return s }
return swiftIdentifier
}
/// return a valid Swift name by appending '_' to a reserved name
var swiftName: String {
guard !reservedNames.contains(self) else { return self + "_" }
return swiftIdentifier
}
/// return a valid Swift name by quoting a reserved name
var swiftQuoted: String {
guard !reservedNames.contains(self) else { return "`" + self + "`" }
return swiftIdentifier
}
/// return a swift representation of an identifier string (escaped if necessary)
var swift: String {
if let s = castableScalars[self] { return s }
if let s = castablePointers[self] { return s }
if let s = swiftReplacementsForC[self] { return s }
let s = swiftType
guard !reservedTypes.contains(s) else { return s + "Type" }
return s.swiftName
}
/// return an idiomatic swift representation of an identifier string (escaped if necessary)
var swiftIdiomatic: String {
if let s = castableScalars[self] { return s }
if let s = castablePointers[self] { return s }
if let s = swiftIdiomaticReplacements[self] { return s }
let s = swiftType
guard !reservedTypes.contains(s) else { return s + "Type" }
return s.swiftName
}
/// return a verbatim swift representation of an identifier string (escaped if necessary)
var swiftVerbatim: String {
if let s = castableScalars[self] { return s }
if let s = castablePointers[self] { return s }
if let s = swiftVerbatimReplacements[self] { return s }
let s = swiftType
guard !reservedTypes.contains(s) else { return s + "Type" }
return s.swiftName
}
/// return a verbatim, idiomatic swift representation of an identifier string (escaped if necessary)
var swiftVerbatimIdiomatic: String {
if let s = castableScalars[self] { return s }
if let s = castablePointers[self] { return s }
if let s = swiftVerbatimIdiomaticReplacements[self] { return s }
let s = swiftType
guard !reservedTypes.contains(s) else { return s + "Type" }
return s.swiftName
}
/// indicate whether the type represented by the receiver is a constant
var isCConst: Bool {
let ns = trimmed
return ns.hasPrefix("const ") || ns.contains(" const")
}
/// indicate whether the given string is a known g pointer type
var isCastablePointer: Bool { return castablePointers[self] != nil }
/// indicate whether the given string is a knowns Swift pointer type
var isSwiftPointer: Bool { return hasSuffix("Pointer") }
/// return the C type without a trailing "const"
var typeWithoutTrailingConst: String { return without(suffix: " const") }
/// return the C type without a trailing "const"
var typeWithoutTrailingVolatile: String { return without(suffix: " volatile") }
/// return the C type without a leading "const"
var typeWithoutLeadingConst: String { return without(prefix: "const ") }
/// return the C type without a leading "volatile"
var typeWithoutLeadingVolatile: String { return without(prefix: "volatile ") }
/// return the C type without a trailing "const" or "volatile"
var typeWithoutTrailingConstOrVolatile: String { return without(suffixes: [" const", " volatile"]) }
/// return the C type without a leading or trailing "const"
var typeWithoutLeadingOrTrailingConst: String {
return typeWithoutLeadingConst.typeWithoutTrailingConst
}
/// return the C type without a leading or trailing "volatile"
var typeWithoutLeadingOrTrailingVolatile: String {
return typeWithoutLeadingVolatile.typeWithoutTrailingVolatile
}
/// return the C type without a leading or trailing "const" or "volatile"
var typeWithoutLeadingOrTrailingConstOrVolatile: String {
return without(suffixes: [" const", " volatile"]).without(prefixes: ["const ", "volatile "])
}
/// return the C type without "const"
var typeWithoutConst: String { return without("const") }
/// return the C type without "volatile"
var typeWithoutVolatile: String { return without("volatile") }
/// return whether the untrimmed string is a C pointer
var isTrimmedCPointer: Bool { return self.hasSuffix("*") }
/// return whether the untrimmed string is a gpointer or gconstpointer
var isTrimmedGPointer: Bool { return self == "gpointer" || self == "gconstpointer" }
/// return whether the untrimmed string is a pointer
var isTrimmedPointer: Bool { return isTrimmedGPointer || isTrimmedCPointer }
/// return whether the underlying C type is a pointer
var isCPointer: Bool {
return typeWithoutTrailingConstOrVolatile.trimmed.isTrimmedCPointer
}
/// return whether the underlying C type is a gpointer
var isGPointer: Bool {
return typeWithoutTrailingConstOrVolatile.trimmed.isTrimmedGPointer
}
/// return whether the underlying C type is a pointer of any kind
var isPointer: Bool {
return typeWithoutTrailingConstOrVolatile.trimmed.isTrimmedPointer
}
/// return the underlying C type for a pointer, nil if not a pointer
var underlyingTypeForCPointer: String? {
guard isCPointer else { return nil }
let ns = typeWithoutTrailingConstOrVolatile
let s = ns.startIndex
let e = ns.index(before: ns.endIndex)
return String(ns[s..<e])
}
/// return the C type unwrapped and converted to Swift
/// - Parameters:
/// - pointerCount: the number of pointer indirections to deal with
/// - constCount: the number of consts
/// - optionalTail: the tail to add, e.g. "?" for optional, "!", for a force-unwrapped optional, or "" for a non-optional pointer
/// - Returns: Tuple of the Swift version of the C type, the Swift-encoded version of the inner type, the pointer and const counts, as well as the inner type
func unwrappedCTypeWithCount(_ pointerCount: Int = 0, _ constCount: Int = 0, optionalTail: String = "!") -> (gType: String, swift: String, pointerCount: Int, constCount: Int, innerType: String) {
if let base = underlyingTypeForCPointer {
let (pointer, cc) = isCConst ? ("UnsafePointer", constCount+1) : ("UnsafeMutablePointer", constCount)
let t = base.unwrappedCTypeWithCount(pointerCount+1, cc, optionalTail: "?")
let wrappedOrig = pointer + "<\(t.gType)>" + optionalTail
let wrappedSwift: String
if t.swift == "Void" {
wrappedSwift = pointer == "UnsafePointer" ? "UnsafeRawPointer" : "UnsafeMutableRawPointer"
} else {
wrappedSwift = pointer + "<\(t.swift)>" + optionalTail
}
return (gType: wrappedOrig, swift: wrappedSwift, pointerCount: t.pointerCount, constCount: t.constCount, innerType: t.innerType)
}
let t = trimmed.typeWithoutLeadingOrTrailingConstOrVolatile
let swiftVersionOfCType = t.swiftType
return (gType: swiftVersionOfCType, swift: t.swift, pointerCount: pointerCount, constCount: constCount, innerType: t)
}
/// return the inner type of a C type (without pointers and const)
var innerCType: String { return unwrappedCTypeWithCount().innerType }
/// return the swift representation of the inner type of a C type (without pointers and const)
var innerGType: String { return innerCType.swiftType }
/// return the common swift type used for the inner type of a C type (without pointers and const)
var innerSwiftType: String { return innerCType.swiftType }
/// return the C type unwrapped, without const, and converted to Swift
var unwrappedCType: String { return unwrappedCTypeWithCount().gType }
/// return the Swift type common for a given C type
var swiftRepresentationOfCType: String { return unwrappedCTypeWithCount().swift }
/// return a split argument name based on splittable prefixes such as "for", "from", "in"
@inlinable var argumentSplit: (prefix: Substring, arg: Substring) {
guard let i = splittablePrefixIndex(from: splittablePrefixes), i != endIndex else { return ("", self[startIndex..<endIndex]) }
let e = index(before: i)
return (prefix: self[startIndex..<e], arg: self[i..<endIndex])
}
}
@usableFromInline let splittablePrefixes = [ "after_", "before_", "for_", "from_", "in_", "of_", "with_", "within_" ]
extension StringProtocol {
/// return a valid Swift name by quoting a reserved name
@usableFromInline var swiftQuoted: String {
let s = String(self)
guard !reservedNames.contains(s) else { return "`" + self + "`" }
return s.swiftIdentifier
}
}
|
bsd-2-clause
|
0a3f57fecfc5225349380efa2a6b8d6d
| 43.002591 | 300 | 0.666235 | 4.057573 | false | false | false | false |
milseman/swift
|
test/stdlib/DispatchTypes.swift
|
36
|
1416
|
// RUN: %target-swift-frontend -typecheck %s
// REQUIRES: objc_interop
import Dispatch
func getAnyValue<T>(_ opt: T?) -> T { return opt! }
// dispatch/io.h
let io = DispatchIO(type: .stream, fileDescriptor: 0, queue: DispatchQueue.main, cleanupHandler: { (error: Int32) -> () in fatalError() })
io.close(flags: .stop)
io.setInterval(interval: .seconds(0), flags: .strictInterval)
// dispatch/queue.h
let q = DispatchQueue(label: "", attributes: [])
_ = DispatchQueue(label: "", attributes: .concurrent)
_ = q.label
if #available(OSX 10.10, iOS 8.0, *) {
_ = DispatchQueue.global(qos: .userInteractive)
_ = DispatchQueue.global(qos: .background)
_ = DispatchQueue.global(qos: .default)
}
// dispatch/source.h
_ = DispatchSource.makeUserDataAddSource()
_ = DispatchSource.makeUserDataOrSource()
_ = DispatchSource.makeMachSendSource(port: mach_port_t(0), eventMask: [])
_ = DispatchSource.makeMachReceiveSource(port: mach_port_t(0))
_ = DispatchSource.makeMemoryPressureSource(eventMask: [])
_ = DispatchSource.makeProcessSource(identifier: 0, eventMask: [])
_ = DispatchSource.makeReadSource(fileDescriptor: 0)
_ = DispatchSource.makeSignalSource(signal: SIGINT)
_ = DispatchSource.makeTimerSource()
_ = DispatchSource.makeFileSystemObjectSource(fileDescriptor: 0, eventMask: [])
_ = DispatchSource.makeWriteSource(fileDescriptor: 0)
// dispatch/time.h
_ = DispatchTime.now()
_ = DispatchTime.distantFuture
|
apache-2.0
|
3202badcab30c5a7aa8fe77af517f4c4
| 35.307692 | 138 | 0.734463 | 3.548872 | false | false | false | false |
jonasman/TeslaSwift
|
Sources/TeslaSwift/Model/RemoteSeatHeaterRequestOptions.swift
|
1
|
881
|
//
// RemoteSeatHeaterRequestOptions.swift
// TeslaSwift
//
// Created by Jordan Owens on 2/17/19.
// Copyright © 2019 Jordan Owens. All rights reserved.
//
import Foundation
open class RemoteSeatHeaterRequestOptions: Encodable {
open var seat: HeatedSeat
open var level: HeatLevel
public init(seat: HeatedSeat, level: HeatLevel) {
self.seat = seat
self.level = level
}
enum CodingKeys: String, CodingKey {
case seat = "heater"
case level = "level"
}
}
public enum HeatedSeat: Int, Encodable {
case driver = 0
case passenger = 1
case rearLeft = 2
case rearLeftBack = 3
case rearCenter = 4
case rearRight = 5
case rearRightBack = 6
case thirdRowLeft = 7
case thirdRowRight = 8
}
public enum HeatLevel: Int, Encodable {
case off = 0
case low = 1
case mid = 2
case high = 3
}
|
mit
|
879f6024642986c8027690ccf99dee31
| 19 | 55 | 0.651136 | 3.548387 | false | false | false | false |
marcopolee/glimglam
|
Glimglam WatchKit Extension/WatchBridge.swift
|
1
|
1963
|
//
// WatchBridge.swift
// Glimglam
//
// Created by Tyrone Trevorrow on 14/10/17.
// Copyright © 2017 Marco Polee. All rights reserved.
//
import Foundation
import WatchConnectivity
class WatchBridge: NSObject, WCSessionDelegate {
enum Message: String {
case GitLabLogin
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
if activationState == .activated {
}
}
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
print("received message (\(userInfo["type"] ?? "invalid message"))")
guard let typeStr = userInfo["type"] as? String,
let type = Message(rawValue: typeStr),
let object = userInfo["object"] as? [String: Any] else {
print("unrecognized message type: version mismatch maybe?")
return
}
switch type {
case .GitLabLogin:
guard let data = try? JSONSerialization.data(withJSONObject: object, options: []),
let newContext = try? JSONDecoder().decode(CoreContext.self, from: data) else {
print("unrecognized message structure: likely programmer derp")
return
}
context.gitLabLogin = newContext.gitLabLogin
context.user = newContext.user
context.storeInKeychain()
}
}
let context: CoreContext
let session: WCSession
init(context: CoreContext) {
self.context = context
self.session = WCSession.default
super.init()
self.session.delegate = self
self.session.activate()
}
func send(object: [String: Any], type: Message) {
let message: [String: Any] = [
"type": type.rawValue,
"object": object
]
session.transferUserInfo(message)
}
}
|
mit
|
a27e55b46f8c17e648ecb3e06629de7f
| 30.645161 | 124 | 0.591743 | 4.762136 | false | false | false | false |
muneebm/AsterockX
|
AsterockX/ObservationCell.swift
|
1
|
2635
|
//
// ObservationCell.swift
// AsterockX
//
// Created by Muneeb Rahim Abdul Majeed on 1/17/16.
// Copyright © 2016 beenum. All rights reserved.
//
import UIKit
class ObservationCell: UICollectionViewCell {
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
@IBOutlet weak var errorMessageLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var observationTimeLabel: UILabel!
var cache: NSCache!
var taskToCancelifCellIsReused: NSURLSessionTask? {
didSet {
if let taskToCancel = oldValue {
taskToCancel.cancel()
}
}
}
func setImage(imageKey: String) {
errorMessageLabel.hidden = true
if let image = cache.objectForKey(imageKey) as? UIImage {
imageView.image = image
}
else {
startActitvityIndicator()
taskToCancelifCellIsReused = Asterank.sharedInstance().imageForKey(imageKey) {
(result, _) -> Void in
if let data = result {
dispatch_sync(dispatch_get_main_queue()) {
if let image = UIImage(data: data) {
self.imageView.image = image
self.cache.setObject(image, forKey: imageKey)
}
else {
self.imageView.image = nil
self.errorMessageLabel.hidden = false
}
}
}
self.stopActivityIndicator()
}
taskToCancelifCellIsReused?.resume()
}
}
func startActitvityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.userInteractionEnabled = false
self.imageView.addSubview(self.activityIndicator)
self.activityIndicator.center = self.contentView.center
self.alpha = 0.75
self.activityIndicator.startAnimating()
}
}
func stopActivityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.activityIndicator.stopAnimating()
self.activityIndicator.removeFromSuperview()
self.alpha = 1
self.userInteractionEnabled = true
}
}
}
|
mit
|
1ae640ab3354f0125be51726cbf5aace
| 28.266667 | 111 | 0.51139 | 5.81457 | false | false | false | false |
tangplin/Scream.swift
|
Scream/UIBarButtonItem.swift
|
1
|
2007
|
//
// UIBarButtonItem.swift
// Scream
//
// Created by Pinglin Tang on 14-10-15.
// Copyright (c) 2014 Pinglin Tang. All rights reserved.
//
import UIKit
public extension UIBarButtonItem {
public func now(action: UIBarButtonItem -> ()) -> UIBarButtonItem {
action(self)
return self
}
public func clicked(label:String = "", action: (UIBarButtonItem -> ())?) -> UIBarButtonItem {
self.__offClicked(label:label)
if action == nil {
return self
}
let proxy = UIBarButtonItemProxy(action!)
self.target = proxy
self.action = "act:"
self.proxies[label] = proxy
return self
}
}
///MARK:- Internal
private var UIBarButtonItemProxiesKey:Void
typealias UIBarButtonItemProxies = [String:UIBarButtonItemProxy]
internal class UIBarButtonItemProxy : NSObject {
var action: UIBarButtonItem -> ()
init(_ action: UIBarButtonItem -> ()) {
self.action = action
}
func act(source: UIBarButtonItem) {
action(source)
}
}
internal extension UIBarButtonItem {
func setter(newValue:UIBarButtonItemProxies) -> UIBarButtonItemProxies {
objc_setAssociatedObject(self, &UIBarButtonItemProxiesKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC));
return newValue
}
var proxies: UIBarButtonItemProxies {
get {
if let result = objc_getAssociatedObject(self, &UIBarButtonItemProxiesKey) as? UIBarButtonItemProxies {
return result
} else {
return setter(UIBarButtonItemProxies())
}
}
set {
setter(newValue)
}
}
func __offClicked(label:String = "") -> UIBarButtonItem {
if let proxy = self.proxies[label] {
self.target = nil
self.action = ""
self.proxies.removeValueForKey(label)
}
return self
}
}
|
mit
|
757cfc24e4e7b00fec6f323171b4cf91
| 23.192771 | 118 | 0.590433 | 5.0175 | false | false | false | false |
sanzhong538/SZChoosePictrue
|
SZChoosePictrue/SZChoosePictrue/GameController.swift
|
2
|
6388
|
//
// GameController.swift
// SZChoosePictrue
//
// Created by 吴三忠 on 16/6/22.
// Copyright © 2016年 吴三忠. All rights reserved.
//
import UIKit
class GameController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {
internal var imageArray: [UIImage]!
internal var image: UIImage!
internal var count: Int!
var emptyCell: GameViewCell?
var stepValue: Int? = 0
var timer: NSTimer!
var time: Int? = 0
var name: String?
var newImageArray:[UIImage]!
@IBOutlet weak var gameImageView: UICollectionView!
@IBOutlet weak var fullImageView: UIImageView!
@IBOutlet weak var viewFlowLayout: UICollectionViewFlowLayout!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var stepLabel: UILabel!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBAction func clickSetButton(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func clickRestartButton(sender: UIButton) {
timer.invalidate()
time = 0
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(creatTime), userInfo: nil, repeats: true)
timer.fire()
stepLabel.text = String(0)
stepValue = 0
newImageArray = changeArrayOrder(imageArray)
gameImageView .reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
fullImageView.image = image
newImageArray = changeArrayOrder(imageArray)
gameImageView.dataSource = self
gameImageView.delegate = self
topConstraint.constant = (view.frame.size.width == CGFloat(320) ?10:50)
let imageWidth = CGFloat(gameImageView.frame.width - CGFloat(count!) - 1)/CGFloat(count!)
viewFlowLayout.itemSize = CGSize(width: imageWidth, height: imageWidth)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(creatTime), userInfo: nil, repeats: true)
timer.fire()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
timer.invalidate()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray!.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("gameCell", forIndexPath: indexPath) as! GameViewCell
cell.index = indexPath.item
cell.imageView.image = nil
if indexPath.item < newImageArray.count {
cell.imageView.image = newImageArray![indexPath.item]
}
else {
emptyCell = cell
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView .cellForItemAtIndexPath(indexPath) as! GameViewCell
let value = abs(cell.index - emptyCell!.index)
if value == count || (value == 1 && cell.index/count! == emptyCell!.index/count!) {
emptyCell?.imageView.image = cell.imageView.image
cell.imageView.image = nil
emptyCell = cell
stepValue! += 1
stepLabel.text = String(stepValue!)
}
if emptyCell!.index == imageArray!.count - 1 {
var isComplete: Bool? = true
for i in 0..<imageArray!.count - 1 {
let indexPath: NSIndexPath = NSIndexPath(forItem: i, inSection: 0)
let cell = gameImageView.cellForItemAtIndexPath(indexPath) as! GameViewCell
let isSame = cell.imageView.image == imageArray[i]
isComplete = isComplete == isSame
if isComplete == false {
break
}
}
if isComplete! == true {
let alertVC = UIAlertController(title: "恭喜过关", message: "牛人,留下您的大名", preferredStyle: UIAlertControllerStyle.Alert)
alertVC.addTextFieldWithConfigurationHandler({ (txtField) in
txtField.delegate = self
})
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default, handler: { (action) in
self.saveRecorder()
self.dismissViewControllerAnimated(false, completion: nil)
})
let restartAction = UIAlertAction(title: "继续", style: UIAlertActionStyle.Default, handler: { (action) in
self.saveRecorder()
self.clickRestartButton(UIButton())
alertVC.dismissViewControllerAnimated(false, completion: nil)
})
alertVC.addAction(cancelAction)
alertVC.addAction(restartAction)
presentViewController(alertVC, animated: true, completion: nil)
}
}
}
func textFieldDidEndEditing(textField: UITextField) {
name = textField.text
}
func saveRecorder() {
print(self.name!, self.time!, self.stepValue!)
RecordDataTool.shareRecord().queue .inDatabase { (db) in
do {
try db.executeUpdate("INSERT INTO Record_score (name, time, step) VALUES (?, ?, ?)", values: [self.name!, self.time!, self.stepValue!])
} catch {
print("error = \(error)")
}
}
}
func changeArrayOrder(array: [UIImage]) -> [UIImage] {
var tempArray = imageArray
tempArray.removeLast()
for _ in 0..<100 {
let num = Int(arc4random_uniform(UInt32(tempArray.count - 1)))
let image = tempArray[num]
tempArray.removeAtIndex(num)
tempArray.insert(image, atIndex: num/count > 1 ? num - count : num + 1 )
}
return tempArray
}
func creatTime() {
let minute = time! / 60
let second = time! % 60
timeLabel.text = String(format: "%02zd:%02zd", minute, second)
time! += 1
}
}
|
apache-2.0
|
2b6827b356fb00fd682e3eb936abd9b4
| 37.652439 | 151 | 0.613504 | 4.999211 | false | false | false | false |
kirthika/AuthenticationLibrary
|
Carthage/Checkouts/JWT/Example/JWTDesktopSwift/JWTDesktopSwift/ViewController.swift
|
1
|
12265
|
//
// ViewController.swift
// JWTDesktopSwift
//
// Created by Lobanov Dmitry on 01.10.16.
// Copyright © 2016 JWTIO. All rights reserved.
//
import Cocoa
import JWT
//import Masonry
import Masonry
enum SignatureValidationType : Int {
case Unknown
case Valid
case Invalid
var color : NSColor {
switch self {
case .Unknown:
return NSColor.darkGray
case .Valid:
return NSColor(calibratedRed: 0, green: 185/255.0, blue: 241/255.0, alpha: 1.0)
case .Invalid:
return NSColor.red
}
}
var title : String {
switch self {
case .Unknown:
return "Signature Unknown"
case .Valid:
return "Signature Valid"
case .Invalid:
return "Signature Invalid"
}
}
}
// MARK - Supply JWT Methods
extension ViewController {
var availableAlgorithms : [JWTAlgorithm] {
return JWTAlgorithmFactory.algorithms() as! [JWTAlgorithm]
}
var availableAlgorithmsNames : [String] {
return self.availableAlgorithms.map {$0.name}
}
var chosenAlgorithmName : String {
return self.algorithmPopUpButton.selectedItem?.title ?? ""
}
var chosenSecretData : Data? {
let secret = self.chosenSecret;
let isBase64Encoded = self.isBase64EncodedSecret;
guard let result = Data(base64Encoded: secret), isBase64Encoded else {
return nil
}
return result
}
var chosenSecret : String {
return self.secretTextField.stringValue
}
var isBase64EncodedSecret : Bool {
return self.secretIsBase64EncodedCheckButton.integerValue == 1
}
func JWT(token: String, skipVerification: Bool) -> [AnyHashable : Any]? {
print("JWT ENCODED TOKEN \(token)")
let algorithmName = self.chosenAlgorithmName
print("JWT Algorithm NAME \(algorithmName)")
let builder = JWTBuilder.decodeMessage(token).algorithmName(algorithmName)!.options(skipVerification as NSNumber)
if (algorithmName != JWTAlgorithmNameNone) {
if let secretData = self.chosenSecretData, isBase64EncodedSecret {
_ = builder?.secretData(secretData)
}
else {
self.secretIsBase64EncodedCheckButton.state = 0
_ = builder?.secret(self.chosenSecret)
}
}
self.builder = builder
guard let decoded = builder?.decode else {
print("JWT ERROR \(builder?.jwtError)")
return nil
}
print("JWT DICTIONARY \(decoded)")
return decoded
}
}
// Refresh UI
extension ViewController {
// #pragma mark - Refresh UI
func refreshUI() {
let textStorage = self.encodedTextView.textStorage!;
let string = textStorage.string;
let range = NSMakeRange(0, string.characters.count);
if let attributedString = self.encodedAttributedString(text: string) {
textStorage.replaceCharacters(in: range, with: attributedString)
}
let jwtVerified = self.JWT(token: string, skipVerification: false) != nil
self.signatureReactOnVerifiedToken(verified: jwtVerified)
self.decriptedViewController.builder = self.builder
}
}
// MARK - Encoding
extension ViewController {
}
// MARK - Actions
extension ViewController {
func popUpButtonValueChanged(sender : AnyClass) {
self.refreshUI()
}
func checkBoxState(sender : AnyClass) {
self.refreshUI()
}
func signatureReactOnVerifiedToken(verified: Bool) {
let type = verified ? SignatureValidationType.Valid : SignatureValidationType.Invalid
self.signatureValidation = type
}
}
extension ViewController : NSTextFieldDelegate {
override func controlTextDidChange(_ obj: Notification) {
if (obj.name == NSNotification.Name.NSControlTextDidChange) {
let textField = obj.object as! NSTextField
if textField == self.secretTextField {
self.refreshUI()
}
}
}
}
// MARK - Encoding Heplers
extension Array {
func safeObject(index: Array.Index) -> Element? {
return index >= self.count ? nil : self[index]
}
}
// Array issues
extension ViewController {
func attributesJoinedBy(_ attributes: [NSAttributedString], by: NSAttributedString) -> NSAttributedString? {
var array = attributes
if let first = array.first {
array.removeFirst()
return array.reduce(first, { (result, string) -> NSAttributedString in
let mutableResult = NSMutableAttributedString(attributedString: result)
mutableResult.append(by)
mutableResult.append(string)
return mutableResult
})
}
return nil
}
}
//extension Sequence where Iterator.Element == NSAttributedString {
// func componentsJoined(by: Iterator.Element) -> Iterator.Element? {
// let array = self
// if let first = array.first(where: {_ in true}) {
// let subarray = array.dropFirst()
// return (Self(subarray) as! Self).reduce(first, {
// (result, part) -> Iterator.Element in
// let mutableResult = NSMutableAttributedString(attributedString: result)
// mutableResult.append(by)
// mutableResult.append(part)
// return mutableResult
// })
// }
// return nil
// }
//}
// Encoding Customization
extension ViewController {
// #pragma mark - Encoding Customization
func textPart(parts: [String], type: TokenTextType) -> String? {
var result: String? = nil
switch type {
case .Header:
result = parts.safeObject(index: 0)
case .Payload:
result = parts.safeObject(index: 1)
case .Signature:
if (parts.count > 2) {
result = (Array(parts[2..<parts.count]) as NSArray).componentsJoined(by: ".")
}
default: result = nil
}
return result
}
func encodedTextAttributes(type: TokenTextType) -> [String: Any] {
var attributes = self.defaultEncodedTextAttributes
attributes[NSForegroundColorAttributeName] = type.color
return attributes
}
var defaultEncodedTextAttributes: [String:Any] {
return [
NSFontAttributeName : NSFont.boldSystemFont(ofSize: 22)
] as [String: Any]
}
func encodedAttributedString(text: String) -> NSAttributedString? {
let parts = (text as NSString).components(separatedBy: ".")
// next step, determine text color!
// add missing dots.
// restore them like this:
// color text if you can
var resultParts: [NSAttributedString] = [];
for typeNumber in TokenTextType.Header.rawValue ... TokenTextType.Signature.rawValue {
let type = TokenTextType(rawValue: typeNumber)
if let currentPart = self.textPart(parts: parts, type: type!) {
let attributes = self.encodedTextAttributes(type: type!)
let currentAttributedString = NSAttributedString(string: currentPart, attributes: attributes)
resultParts.append(currentAttributedString)
}
}
let attributes = self.encodedTextAttributes(type: .Default)
let dot = NSAttributedString(string: ".", attributes: attributes)
let result = self.attributesJoinedBy(resultParts, by: dot)
return result
}
}
// MARK - EncodingTextViewDelegate
extension ViewController : NSTextViewDelegate {
func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
if (textView == self.encodedTextView) {
if let textStore = textView.textStorage {
textStore.replaceCharacters(in: affectedCharRange, with: replacementString!)
}
self.refreshUI()
return false
}
return false
}
}
class ViewController: NSViewController {
override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
// Properties - Outlets
@IBOutlet weak var algorithmLabel : NSTextField!
@IBOutlet weak var algorithmPopUpButton : NSPopUpButton!
@IBOutlet weak var secretLabel : NSTextField!
@IBOutlet weak var secretTextField : NSTextField!
@IBOutlet weak var secretIsBase64EncodedCheckButton : NSButton!
@IBOutlet weak var encodedTextView : NSTextView!
@IBOutlet weak var decriptedView : NSView!
var decriptedViewController : DecriptedViewController!
@IBOutlet weak var signatureStatusLabel : NSTextField!
// Properties - Data
var signatureDecorations : NSDictionary = [:]
var signatureValidation : SignatureValidationType = .Unknown {
didSet {
self.signatureStatusLabel.backgroundColor = signatureValidation.color
self.signatureStatusLabel.stringValue = signatureValidation.title
}
}
// Properties - Tests
var builder : JWTBuilder?;
// MARK - Setup
func setupTop() {
// top label.
self.algorithmLabel.stringValue = "Algorithm";
// pop up button.
self.algorithmPopUpButton.removeAllItems()
self.algorithmPopUpButton.addItems(withTitles: self.availableAlgorithmsNames)
self.algorithmPopUpButton.target = self
self.algorithmPopUpButton.action = #selector(ViewController.popUpButtonValueChanged(sender:))
// secretLabel
self.secretLabel.stringValue = "Secret"
// secretTextField
self.secretTextField.placeholderString = "Secret"
self.secretTextField.delegate = self
// check button
self.secretIsBase64EncodedCheckButton.title = "is Base64Encoded Secret"
self.secretIsBase64EncodedCheckButton.integerValue = 0
self.secretIsBase64EncodedCheckButton.target = self
self.secretIsBase64EncodedCheckButton.action = #selector(ViewController.checkBoxState(sender:))
}
func setupBottom() {
self.signatureStatusLabel.alignment = .center
self.signatureStatusLabel.textColor = NSColor.white
self.signatureStatusLabel.drawsBackground = true
self.signatureValidation = .Unknown
}
func setupEncodingDecodingViews() {
self.encodedTextView.delegate = self;
}
func setupDecorations() {
self.setupTop()
self.setupBottom()
}
func setupDecriptedViews() {
let view = self.decriptedView
self.decriptedViewController = DecriptedViewController()
view?.addSubview(self.decriptedViewController.view)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupDecorations()
self.setupEncodingDecodingViews()
self.setupDecriptedViews()
self.defaultJWTIOSetup()
self.refreshUI()
}
func defaultJWTIOSetup() {
// secret
self.secretTextField.stringValue = "secret"
// token
self.encodedTextView.string = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
// algorithm HS256
if let index = self.availableAlgorithmsNames.index(where: {
$0 == JWTAlgorithmNameHS256
}) {
self.algorithmPopUpButton.selectItem(at: index)
}
}
override func viewWillAppear() {
super.viewWillAppear()
let view = self.decriptedView
let subview = self.decriptedViewController.view
subview.mas_makeConstraints { (make) in
_ = make?.edges.equalTo()(view)
}
}
}
|
mit
|
0237a79cceaed9c439c69dac72844fd2
| 31.104712 | 189 | 0.626142 | 4.783151 | false | false | false | false |
libzhu/LearnSwift
|
扩展/MyPlayground.playground/Contents.swift
|
1
|
8810
|
//: Playground - noun: a place where people can play
import UIKit
var str = "扩展"
/*
· 扩展语法
· 计算型属性
· 构造器
· 方法
· 下标
· 嵌套类型
*/
//扩展 就是为了一个已有的类、结构体、枚举类型或者协议类型添加新功能。这包括在没有权限获取到源代码的情况下扩展类型的能力(即逆向建模)。扩展和Objective-C中的分类类似。
//Swift中的扩展可以:
/*
· 添加计算性属性和计算型类型属性
· 定义实例方法和类型方法
· 提供新的构造器
· 定义下标
· 定义和使用新的嵌套类型
· 使一个已有类型符合某个协议
*/
//在swift中 甚至可以对协议进行扩展,提供协议要求的实现。或者添加额外的功能, 从而可以让符合协议的类型拥有这些功能。
//注意可以为一个类型添加新的功能, 但是不能重写已有的功能。
//1、扩展语法
//使用关键字 extension 来声明扩展
//extension SomeType {
//
// //为someType 添加新的功能
//}
//可以通过扩展一个已有的类型,使其采纳一个或多个协议。这种情况下,无论是类 结构体, 协议名字的书写方式完全一样
//extension SomeType : SomeProtocol, AnohterProtocol {
//
// //协议的实现写在这里。
//}
//计算性属性
//扩展可以为已有类型添加实例属性和计算类型属性,下面的例子中Swift 的内建 Double 类型添加了五个计算属性实例, 从而提供与距离单位协作的基本支持:
extension Double {
var km : Double { return self * 1_000.0 }
var m : Double { return self }
var cm : Double { return self / 100.0 }
var mm : Double { return self / 1_000.0 }
var ft : Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("one Inch is \(oneInch) meters")
let threeFeet = 3.ft
print("three feet is \(threeFeet) meters")
let fiveM = 5.m
print("five mi \(fiveM)")
//这些计算属性表达式的含义是把 一个 Double 值看作是某个单位下的长度值。即使把他们实现为计算型属性,但这些属性的名字人可以紧接着一个浮点型字面值, 从而通过点语法来使用, 并以此实现距离转换。
//上述例子中, Double 值 1.0 用来表示1米, 这就是为什么计算属性m 返回的self, 及表达式1.m 被认为计算Double值 1.0;
//其他单位则需要一些换算, 一千米等于1000米, 所以计算属性km 要把值乘以1_000.0来实现千米到米的单位换算, 类似的,一米有3.28024英尺, 所以计算型属性 ft 要把对应的 Double值除以 3.28024来实现英尺对米的单位换算。
//这些属性是只读的计算属性,为了更简洁, 省略了 get 关键字。 他们的返回值 是 Double 而且可以用于所有接受Double 值的数学计算中
let aMarathon = 42.km + 195.ft
print("A marathon is \(aMarathon) meters long")
//注意:扩展可以添加新的计算型属性, 但是不可以添加存储型属性, 也不可以为已有的属性添加属性观察器。
//构造器
//扩展可以为已有类型添加新的构造器。这可以让你扩展其他类型, 将你自己定制的类型作为其构造器构造器参数, 或者提供该类型的原始实现中未提供的额外的初始化选项。
//扩展能为类添加新的便利构造器 但是他们不能为类添加新的指定构造器或析构器, 指定构造器和析构器必须总是由原始的类实现来提供的。
//注意:如果你使用扩展为值类型添加构造器,同时该值类型的原始实现中未定义任何定制的构造器切所有的存储属性提供了默认值, 那么我们可以在扩展中的构造器里调用默认构造器和逐一成员构造器。正如在 值类型的构造器代理中描述的, 如果你把定制的构造器写在值类型的原始实现中 上述规则将不再实用。
//下面的例子:定义了一个描述几何矩形的结构体 Rect 这个例子同时定义了连个辅助结构体Size 和 Point 它们都把 0.0 作为所有属性的默认值
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var size = Size()
var origin = Point()
}
//以为结构体Rect 未提供 定制的构造器, 因此它会获得一个逐一成员构造器,应为它又对所有存储属性都提供了默认值, 他又会获得一个默认值构造器,
let defaultRect = Rect()//默认构造器
let memberwiseRect = Rect(size : Size(width : 5.0, height : 5.0), origin : Point(x : 2.0 , y : 2.0))
//可以提供一个额外的接受指定中心点和大小的构造器来扩展 Rect 结构体
extension Rect {
init(center : Point, size : Size) {
let originX = center.x - size.width / 2
let originY = center.y - size.height / 2
self.init(size : size, origin : Point(x : originX, y : originY))
}
}
//这个新的构造器首先根据提供的 center 和 size 的值计算一个合适的原点。 然后调用结构体的主意成员构造器 init(origin: size:)该原点将新的原点和大小的值保存在相应的属性中
let centerRect = Rect(center : Point(x : 4.0, y : 4.0), size : Size(width : 3.0, height : 3.0))
print(centerRect.origin, centerRect.size)
//方法:
//扩展可以为已有类型的添加新的实例方法和类型方法。下面的例子为Int 类型添加了一个名为repetitions 的实例方法。
extension Int {
func repetitions(task : () -> Void) {
for _ in 0..<self {
task()
}
}
}
//这个 repetition(task : )方法接受一个 ()—> Void 类型的单参数, 表示没有参数没有返回值的函数。定义该扩展之后, 你就可以对任意整数调用repetition(task:)方法, 将闭包中的任务执行整数对应的次数。
7.repetitions {
print("good")
}
3.repetitions {
print("hello")
}
//可变实例方法
//通过扩展添加的实例方法也可以修改该实例本事。结构体和枚举类型中修改self 或其属性的方法必须将该实例方法 标注为 mutating (变化、可变)正如来自原始实现的可变方法一样。
//下面的例子:Int 类型添加了一个名为square 的可变方法,用于计算原始值的平方
extension Int{
mutating func square(){
self = self * self
}
}
var someInt = 3
someInt.square()
print(someInt)
//下标
//扩展可以为已有类型添加新下标。
//例子:为Int类型添加了一个整型下标。该下标【n】返回十进制数字从右向左的第n个数字。
// 123456789[0] 返回 9 123456789[1] 返回8
extension Int {
subscript(digitIndex : Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
7438[0]
124252353523[9]
//如果该 Int 值没有足够的位数,即下标越界,那么上述下标实现会返回 0,犹如在数字左边自动补 0:
746381295[9]
// 返回 0,即等同于:
0746381295[9]
//嵌套类型
//扩展可以为已有的类、结构体和枚举调添加新的嵌套类型
extension Int {
enum Kind {
case Negative, Zero, Positive
}
var kind : Kind {
switch self {
case 0:
return .Zero
case let x where x > 0:
return .Positive
default:
return .Negative
}
}
}
//为Int 添加了嵌套枚举。 这个Kind 的枚举表示特定整数的类型。具体说就是表示整数 负数 和 零。还为Int 添加了一个计算型实例属性, 即kind 用来根据整型返回适当的Kind 成员
func printIntegerKinds(_ numbers : [Int]) {
for number in numbers {
switch number.kind {
case .Negative:
print("- ", terminator: "")
case .Positive:
print("+ ", terminator: "")
case .Zero:
print("0 ", terminator: "")
}
}
print("")
}
printIntegerKinds([3,4,-17, 44, 0, 5, -21, -9, 0])
//函数 printIntegerKinds(_:) 接受一个 Int 数组,然后对该数组进行迭代。在每次迭代过程中,对当前整数的计算型属性 kind 的值进行评估,并打印出适当的描述。
//注意
//由于已知 number.kind 是 Int.Kind 类型,因此在 switch 语句中,Int.Kind 中的所有成员值都可以使用简写形式,例如使用 . Negative 而不是 Int.Kind.Negative。
|
mit
|
e5f75d07dafcaacb93b7b6ebb1595376
| 20.467742 | 143 | 0.642938 | 2.54615 | false | false | false | false |
DanielOram/ios-gyro-app-swift
|
ios-gyro-app-swift/MotionKit.swift
|
1
|
16406
|
//
// MotionKit.swift
// MotionKit
//
// Created by Haroon on 14/02/2015.
// Launched under the Creative Commons License. You're free to use MotionKit.
//
// The original Github repository is https://github.com/MHaroonBaig/MotionKit
// The official blog post and documentation is https://medium.com/@PyBaig/motionkit-the-missing-ios-coremotion-wrapper-written-in-swift-99fcb83355d0
//
import Foundation
import CoreMotion
//_______________________________________________________________________________________________________________
// this helps retrieve values from the sensors.
@objc protocol MotionKitDelegate {
optional func retrieveAccelerometerValues (x: Double, y:Double, z:Double, absoluteValue: Double)
optional func retrieveGyroscopeValues (x: Double, y:Double, z:Double, absoluteValue: Double)
optional func retrieveDeviceMotionObject (deviceMotion: CMDeviceMotion)
optional func retrieveMagnetometerValues (x: Double, y:Double, z:Double, absoluteValue: Double)
optional func getAccelerationValFromDeviceMotion (x: Double, y:Double, z:Double)
optional func getGravityAccelerationValFromDeviceMotion (x: Double, y:Double, z:Double)
optional func getRotationRateFromDeviceMotion (x: Double, y:Double, z:Double)
optional func getMagneticFieldFromDeviceMotion (x: Double, y:Double, z:Double)
optional func getAttitudeFromDeviceMotion (attitude: CMAttitude)
}
@objc(MotionKit) public class MotionKit :NSObject{
let manager = CMMotionManager()
var delegate: MotionKitDelegate?
/*
* init:void:
*
* Discussion:
* Initialises the MotionKit class and throw a Log with a timestamp.
*/
public override init(){
NSLog("MotionKit has been initialised successfully")
}
/*
* getAccelerometerValues:interval:values:
*
* Discussion:
* Starts accelerometer updates, providing data to the given handler through the given queue.
* Note that when the updates are stopped, all operations in the
* given NSOperationQueue will be cancelled. You can access the retrieved values either by a
* Trailing Closure or through a Delgate.
*/
public func getAccelerometerValues (interval: NSTimeInterval = 0.1, values: ((x: Double, y: Double, z: Double) -> ())? ){
var valX: Double!
var valY: Double!
var valZ: Double!
if manager.accelerometerAvailable {
manager.accelerometerUpdateInterval = interval
manager.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: {
(data, error) in
if let isError = error {
NSLog("Error: %@", isError)
}
valX = data!.acceleration.x
valY = data!.acceleration.y
valZ = data!.acceleration.z
if values != nil{
values!(x: valX,y: valY,z: valZ)
}
let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ)
self.delegate?.retrieveAccelerometerValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal)
})
} else {
NSLog("The Accelerometer is not available")
}
}
/*
* getGyroValues:interval:values:
*
* Discussion:
* Starts gyro updates, providing data to the given handler through the given queue.
* Note that when the updates are stopped, all operations in the
* given NSOperationQueue will be cancelled. You can access the retrieved values either by a
* Trailing Closure or through a Delegate.
*/
public func getGyroValues (interval: NSTimeInterval = 0.1, values: ((x: Double, y: Double, z:Double) -> ())? ) {
var valX: Double!
var valY: Double!
var valZ: Double!
if manager.gyroAvailable{
manager.gyroUpdateInterval = interval
manager.startGyroUpdatesToQueue(NSOperationQueue(), withHandler: {
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
valX = data!.rotationRate.x
valY = data!.rotationRate.y
valZ = data!.rotationRate.z
if values != nil{
values!(x: valX, y: valY, z: valZ)
}
let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ)
self.delegate?.retrieveGyroscopeValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal)
})
} else {
NSLog("The Gyroscope is not available")
}
}
/*
* getMagnetometerValues:interval:values:
*
* Discussion:
* Starts magnetometer updates, providing data to the given handler through the given queue.
* You can access the retrieved values either by a Trailing Closure or through a Delegate.
*/
@available(iOS, introduced=5.0)
public func getMagnetometerValues (interval: NSTimeInterval = 0.1, values: ((x: Double, y:Double, z:Double) -> ())? ){
var valX: Double!
var valY: Double!
var valZ: Double!
if manager.magnetometerAvailable {
manager.magnetometerUpdateInterval = interval
manager.startMagnetometerUpdatesToQueue(NSOperationQueue()){
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
valX = data!.magneticField.x
valY = data!.magneticField.y
valZ = data!.magneticField.z
if values != nil{
values!(x: valX, y: valY, z: valZ)
}
let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ)
self.delegate?.retrieveMagnetometerValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal)
}
} else {
NSLog("Magnetometer is not available")
}
}
/* MARK :- DEVICE MOTION APPROACH STARTS HERE */
/*
* getDeviceMotionValues:interval:values:
*
* Discussion:
* Starts device motion updates, providing data to the given handler through the given queue.
* Uses the default reference frame for the device. Examine CMMotionManager's
* attitudeReferenceFrame to determine this. You can access the retrieved values either by a
* Trailing Closure or through a Delegate.
*/
public func getDeviceMotionObject (interval: NSTimeInterval = 0.1, values: ((deviceMotion: CMDeviceMotion) -> ())? ) {
if manager.deviceMotionAvailable{
manager.deviceMotionUpdateInterval = interval
manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
if values != nil{
values!(deviceMotion: data!)
}
self.delegate?.retrieveDeviceMotionObject!(data!)
}
} else {
NSLog("Device Motion is not available")
}
}
/*
* getAccelerationFromDeviceMotion:interval:values:
* You can retrieve the processed user accelaration data from the device motion from this method.
*/
public func getAccelerationFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double) -> ())? ) {
var valX: Double!
var valY: Double!
var valZ: Double!
if manager.deviceMotionAvailable{
manager.deviceMotionUpdateInterval = interval
manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
valX = data!.userAcceleration.x
valY = data!.userAcceleration.y
valZ = data!.userAcceleration.z
if values != nil{
values!(x: valX, y: valY, z: valZ)
}
self.delegate?.getAccelerationValFromDeviceMotion!(valX, y: valY, z: valZ)
}
} else {
NSLog("Device Motion is unavailable")
}
}
/*
* getGravityAccelerationFromDeviceMotion:interval:values:
* You can retrieve the processed gravitational accelaration data from the device motion from this
* method.
*/
public func getGravityAccelerationFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double) -> ())? ) {
var valX: Double!
var valY: Double!
var valZ: Double!
if manager.deviceMotionAvailable{
manager.deviceMotionUpdateInterval = interval
manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
valX = data!.gravity.x
valY = data!.gravity.y
valZ = data!.gravity.z
if values != nil{
values!(x: valX, y: valY, z: valZ)
}
_ = sqrt(valX * valX + valY * valY + valZ * valZ)
self.delegate?.getGravityAccelerationValFromDeviceMotion!(valX, y: valY, z: valZ)
}
} else {
NSLog("Device Motion is not available")
}
}
/*
* getAttitudeFromDeviceMotion:interval:values:
* You can retrieve the processed attitude data from the device motion from this
* method.
*/
public func getAttitudeFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((attitude: CMAttitude) -> ())? ) {
if manager.deviceMotionAvailable{
manager.deviceMotionUpdateInterval = interval
manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
if values != nil{
values!(attitude: data!.attitude)
}
self.delegate?.getAttitudeFromDeviceMotion!(data!.attitude)
}
} else {
NSLog("Device Motion is not available")
}
}
/*
* getRotationRateFromDeviceMotion:interval:values:
* You can retrieve the processed rotation data from the device motion from this
* method.
*/
public func getRotationRateFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double) -> ())? ) {
var valX: Double!
var valY: Double!
var valZ: Double!
if manager.deviceMotionAvailable{
manager.deviceMotionUpdateInterval = interval
manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
valX = data!.rotationRate.x
valY = data!.rotationRate.y
valZ = data!.rotationRate.z
if values != nil{
values!(x: valX, y: valY, z: valZ)
}
_ = sqrt(valX * valX + valY * valY + valZ * valZ)
self.delegate?.getRotationRateFromDeviceMotion!(valX, y: valY, z: valZ)
}
} else {
NSLog("Device Motion is not available")
}
}
/*
* getMagneticFieldFromDeviceMotion:interval:values:
* You can retrieve the processed magnetic field data from the device motion from this
* method.
*/
public func getMagneticFieldFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double, accuracy: Int32) -> ())? ) {
var valX: Double!
var valY: Double!
var valZ: Double!
var valAccuracy: Int32!
if manager.deviceMotionAvailable{
manager.deviceMotionUpdateInterval = interval
manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){
(data, error) in
if let isError = error{
NSLog("Error: %@", isError)
}
valX = data!.magneticField.field.x
valY = data!.magneticField.field.y
valZ = data!.magneticField.field.z
valAccuracy = data!.magneticField.accuracy.rawValue
if values != nil{
values!(x: valX, y: valY, z: valZ, accuracy: valAccuracy)
}
self.delegate?.getMagneticFieldFromDeviceMotion!(valX, y: valY, z: valZ)
}
} else {
NSLog("Device Motion is not available")
}
}
/* MARK :- DEVICE MOTION APPROACH ENDS HERE */
/*
* From the methods hereafter, the sensor values could be retrieved at
* a particular instant, whenever needed, through a trailing closure.
*/
/* MARK :- INSTANTANIOUS METHODS START HERE */
public func getAccelerationAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){
self.getAccelerationFromDeviceMotion(0.5) { (x, y, z) -> () in
values(x: x,y: y,z: z)
self.stopDeviceMotionUpdates()
}
}
public func getGravitationalAccelerationAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){
self.getGravityAccelerationFromDeviceMotion(0.5) { (x, y, z) -> () in
values(x: x,y: y,z: z)
self.stopDeviceMotionUpdates()
}
}
public func getAttitudeAtCurrentInstant (values: (attitude: CMAttitude) -> ()){
self.getAttitudeFromDeviceMotion(0.5) { (attitude) -> () in
values(attitude: attitude)
self.stopDeviceMotionUpdates()
}
}
public func getMageticFieldAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){
self.getMagneticFieldFromDeviceMotion(0.5) { (x, y, z, accuracy) -> () in
values(x: x,y: y,z: z)
self.stopDeviceMotionUpdates()
}
}
public func getGyroValuesAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){
self.getRotationRateFromDeviceMotion(0.5) { (x, y, z) -> () in
values(x: x,y: y,z: z)
self.stopDeviceMotionUpdates()
}
}
/* MARK :- INSTANTANIOUS METHODS END HERE */
/*
* stopAccelerometerUpdates
*
* Discussion:
* Stop accelerometer updates.
*/
public func stopAccelerometerUpdates(){
self.manager.stopAccelerometerUpdates()
NSLog("Accelaration Updates Status - Stopped")
}
/*
* stopGyroUpdates
*
* Discussion:
* Stops gyro updates.
*/
public func stopGyroUpdates(){
self.manager.stopGyroUpdates()
NSLog("Gyroscope Updates Status - Stopped")
}
/*
* stopDeviceMotionUpdates
*
* Discussion:
* Stops device motion updates.
*/
public func stopDeviceMotionUpdates() {
self.manager.stopDeviceMotionUpdates()
NSLog("Device Motion Updates Status - Stopped")
}
/*
* stopMagnetometerUpdates
*
* Discussion:
* Stops magnetometer updates.
*/
@available(iOS, introduced=5.0)
public func stopmagnetometerUpdates() {
self.manager.stopMagnetometerUpdates()
NSLog("Magnetometer Updates Status - Stopped")
}
}
|
mit
|
cefd3d2c824a8ae4396ceb9cc1e6a28c
| 35.218543 | 150 | 0.552176 | 5.099782 | false | false | false | false |
wibosco/ConvenientFileManager
|
ConvenientFileManager/Documents/FileManager+Documents.swift
|
1
|
4678
|
//
// FileManager+Documents.swift
// ConvenientFileManager
//
// Created by William Boles on 29/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import Foundation
/// A collection of helper functions for common operations in the documents directory.
public extension FileManager {
// MARK: - Documents
/**
Path of documents directory.
- Returns: String instance.
*/
@objc(cfm_documentsDirectoryPath)
public class func documentsDirectoryPath() -> String {
return (FileManager.documentsDirectoryURL().path)
}
/**
URL of documents directory.
- Returns: URL instance.
*/
@objc(cfm_documentsDirectoryURL)
public class func documentsDirectoryURL() -> URL {
return FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last!
}
/**
Path of resource in documents directory.
- Parameter relativePath: relative path that will be combined documents path.
- Returns: Combined path.
*/
@objc(cfm_documentsDirectoryPathForResourceWithRelativePath:)
public class func documentsDirectoryPathForResource(relativePath: String) -> String {
guard relativePath.count > 0 else {
return FileManager.documentsDirectoryPath()
}
let documentsDirectory = FileManager.documentsDirectoryURL()
let absoluteURL = documentsDirectory.appendingPathComponent(relativePath)
return absoluteURL.path
}
// MARK: - Write
/**
Write/Save data to path in documents directory.
- Parameter data: data to be saved.
- Parameter relativePath: relative path that will be combined documents path.
- Returns: Bool if save was successful.
*/
@objc(cfm_writeData:toDocumentsDirectoryWithRelativePath:)
@discardableResult
public class func writeToDocumentsDirectory(data: Data, relativePath: String) -> Bool {
guard relativePath.count > 0 && data.count > 0 else {
return false
}
let documentsDirectory = FileManager.documentsDirectoryURL()
let absolutePath = documentsDirectory.appendingPathComponent(relativePath).path
return FileManager.write(data: data, absolutePath: absolutePath)
}
// MARK: - Retrieval
/**
Retrieve data to path in documents directory.
- Parameter relativePath: relative path that will be combined documents path.
- Returns: NSData that was retrieved or nil if it's not found.
*/
@objc(cfm_retrieveDataFromDocumentsDirectoryWithRelativePath:)
public class func retrieveDataFromDocumentsDirectory(relativePath: String) -> Data? {
guard relativePath.count > 0 else {
return nil
}
let documentsDirectory = FileManager.documentsDirectoryURL()
let absolutePath = documentsDirectory.appendingPathComponent(relativePath).path
return FileManager.retrieveData(absolutePath: absolutePath)
}
// MARK: - Exists
/**
Determines if a file exists at path in the documents directory
- Parameter relativePath: relative path that will be combined documents path.
- Returns: Bool - true if file exists, false if file doesn't exist.
*/
@objc(cfm_fileExistsInDocumentsDirectoryWithRelativePath:)
public class func fileExistsInDocumentsDirectory(relativePath: String) -> Bool {
guard relativePath.count > 0 else {
return false
}
let documentsDirectory = FileManager.documentsDirectoryURL()
let absolutePath = documentsDirectory.appendingPathComponent(relativePath).path
return FileManager.fileExists(absolutePath: absolutePath)
}
// MARK: - Deletion
/**
Delete data from path in documents directory.
- Parameter relativePath: relative path that will be combined documents path.
- Returns: Bool - true if deletion was successful, false otherwise.
*/
@objc(cfm_deleteDataFromDocumentsDirectoryWithRelativePath:)
@discardableResult
public class func deleteDataFromDocumentsDirectory(relativePath: String) -> Bool {
guard relativePath.count > 0 else {
return false
}
let documentsDirectory = FileManager.documentsDirectoryURL()
let absolutePath = documentsDirectory.appendingPathComponent(relativePath).path
return FileManager.deleteData(absolutePath: absolutePath)
}
}
|
mit
|
9d54cbbc569c78ff23a52fdc8d9f401b
| 32.170213 | 154 | 0.673081 | 5.696711 | false | false | false | false |
WeezLabs/rwauth-ios
|
Tests/MockSession.swift
|
1
|
3280
|
//
// MockSession.swift
// RWAuth
//
// Created by Роман on 28.10.15.
// Copyright © 2015 weezlabs. All rights reserved.
//
import Foundation
class MockSession: NSURLSession {
var fakeRequest: FakeRequest?
var fakeAnswer: FakeAnswer?
func stubRequest(method: String, url: String, requestBody: [String: AnyObject], returnCode: Int, answerBody: [String: AnyObject]) -> Void {
fakeRequest = FakeRequest(method: method, url: url, body: requestBody)
fakeAnswer = FakeAnswer(code: returnCode, body: answerBody)
}
override class func sharedSession() -> NSURLSession {
return MockSession()
}
override func uploadTaskWithRequest(request: NSURLRequest, fromData bodyData: NSData?,
completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionUploadTask {
var error: NSError? = MockSessionError.UnrecognizedError.error
let invalidTask = MockTask() { () -> Void in
completionHandler(nil, nil, error)
}
guard let fakeRequest = fakeRequest, fakeAnswer = fakeAnswer else {
error = MockSessionError.FakeRequestOrFakeAnswerNotSetted.error
return invalidTask
}
// FIXME: handle empty bodyData
guard let bodyData = bodyData else {
error = MockSessionError.EmptyBodyData.error
return invalidTask
}
guard let bodyString = String(data: bodyData, encoding: NSUTF8StringEncoding) else {
error = MockSessionError.BodyDataNotConvertableToString.error
return invalidTask
}
guard request.HTTPMethod == fakeRequest.requestMethod else {
error = MockSessionError.HTTPMethodsNotEqual.error
return invalidTask
}
guard let url = request.URL else {
error = MockSessionError.RequestDoesNotHaveURL.error
return invalidTask
}
guard url.absoluteString == fakeRequest.requestURL else {
error = MockSessionError.StubbedURLNotEqualRequestURL.error
return invalidTask
}
guard let stubedBodyData = try? NSJSONSerialization.dataWithJSONObject(fakeRequest.requestBody,
options: NSJSONWritingOptions(rawValue: 0)) else { return invalidTask }
guard let stubedBodyString = String(data: stubedBodyData, encoding: NSUTF8StringEncoding) else { return invalidTask }
guard bodyString == stubedBodyString else {
error = MockSessionError.StubbedRequestBodyNotEqualRequestBody.error
return invalidTask
}
guard let responseData = try? NSJSONSerialization.dataWithJSONObject(fakeAnswer.answerBody, options: NSJSONWritingOptions(rawValue: 0)) else { return invalidTask }
let urlResponse = NSHTTPURLResponse(URL: url, statusCode: fakeAnswer.answerCode, HTTPVersion: nil, headerFields: nil)
return MockTask() { () -> Void in
completionHandler(responseData, urlResponse, nil)
}
}
}
|
mit
|
6bef150787f23401903cf030f82a727b
| 42.653333 | 175 | 0.62248 | 5.577513 | false | false | false | false |
liuweihaocool/iOS_06_liuwei
|
新浪微博_swift/新浪微博_swift/class/Main/Main/View/LWVistorView.swift
|
1
|
11372
|
//
// LWVistorView.swift
// 新浪微博_swift
//
// Created by liuwei on 15/11/23.
// Copyright © 2015年 liuwei. All rights reserved.
//
import UIKit
protocol LWVistorViewDelegate: NSObjectProtocol {
// 登陆按钮点击
func vistorViewLoginClick()
func vistorViewRegisterClick()
}
/*
frame:
origin:位置(相对父控件)
size:设置大小(写死的数值)
autolayout:
位置:参照比较丰富
大小:参照比较丰富
*/
// 访客视图
class LWVistorView: UIView {
// 设置代理属性
weak var delegate: LWVistorViewDelegate?
// MARK: - 登陆按钮点击事件
func loginClick() {
delegate?.vistorViewLoginClick()
}
func vistorViewRegisterClick() {
delegate?.vistorViewRegisterClick()
}
// swift默认所有的view都能通过 xib 、storyboard 加载
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - 转轮动画 核心动画
func rotationAnimation() {
// 核心动画 旋转
let rotation = CABasicAnimation(keyPath: "transform.rotation")
// 设置动画参数
rotation.toValue = 2 * M_PI
rotation.duration = 20
rotation.repeatCount = MAXFLOAT
// 当不可见的时候 系统会认为动画完成,在完成的时候不要移除动画
rotation.removedOnCompletion = false
// 开始核心动画
iconView.layer.addAnimation(rotation, forKey: "rotation")
}
// MARK: - 核心动画开始和暂停
func pauseAnimation() {
// 获取暂停时间
let pauseTime = iconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
// 设置动画速度为1
iconView.layer.speed = 0
//
iconView.layer.timeOffset = pauseTime
}
func resumeAnimation() {
//获取暂停时间
let pauseTime = iconView.layer.timeOffset
// 设置动画速度为1
iconView.layer.speed = 1
iconView.layer.timeOffset = 0
iconView.layer.beginTime = 0
let timeSincePause = iconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pauseTime
iconView.layer.beginTime = timeSincePause
}
// MARK: - 设置访客视图的内容
func setupVistorView (imageName: String, message: String) {
// 图片 替换转轮的图片
iconView.image = UIImage(named: imageName)
// 文字
messageLabel.text = message
// 适应大小fffff
messageLabel.sizeToFit()
// 隐藏房子
homeView.hidden = true
converView.hidden = true
// self.sendSubviewToBack(converView)
// self.bringSubviewToFront(converView)
}
//准备UI
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
// 添加子控件
private func prepareUI() {
addSubview(iconView)
addSubview(converView)
addSubview(homeView)
addSubview(messageLabel)
addSubview(loginBtn)
addSubview(registerBtn)
//添加结束 autolayout 注意:要设置约束的view 有父控件 后才能设置他的自动布局约束
//关闭autoresizing,不要让他干扰antolayout 的约束 约束需要添加到view上面如果
//如果不清楚添加到自身还是父控件,可以直接添加到父控件
iconView.translatesAutoresizingMaskIntoConstraints = false
homeView.translatesAutoresizingMaskIntoConstraints = false
loginBtn.translatesAutoresizingMaskIntoConstraints = false
converView.translatesAutoresizingMaskIntoConstraints = false
registerBtn.translatesAutoresizingMaskIntoConstraints = false
messageLabel.translatesAutoresizingMaskIntoConstraints = false
/*
创建约束对象 iconView CenterX与父控件的centerX重合
*/
/**
*
*
* @param iconView 被约束的对象
* @param NSLayoutAttribute.CenterX 被约束对象的 轴
* @param NSLayoutRelation.Equal 被约束对象与约束对象的关系 大于 等于 小于
* @param self 被约束对象的父控件
* @param NSLayoutAttribute.CenterX 被约束对象的父控件 的 那个 轴
* @param 1 倍数
* @param 0 坐标偏移
*
* @return
*/
// 转盘
self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -80))
// 小房子
self.addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
// 文本框
self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 60))
self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 250))
// 注册按钮
self.addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
self.addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 90))
self.addConstraint(NSLayoutConstraint(item: registerBtn, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35))
// 登陆按钮
self.addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
self.addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 90))
self.addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35))
/// 遮罩约束
self.addConstraint(NSLayoutConstraint(item: converView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: converView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: converView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: converView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: registerBtn, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 40))
}
// 懒加载 小房子
private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon" ))
// 懒加载 转轮
private lazy var homeView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
// 懒加载 消息label
private lazy var messageLabel: UILabel = {
//创建 label
let label = UILabel()
//设置字体颜色
label.textColor = UIColor.darkGrayColor()
//添加文字
label.text = "关注一群人,走走停停,看看有什么惊喜"
//设置换行 0 为自动
label.numberOfLines = 0
label.sizeToFit()
return label
}()
/// 懒加载 登陆按钮
private lazy var loginBtn: UIButton = {
//实例化
let btn = UIButton()
//设置按钮的背景图片
btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
//设置文字
btn.setTitle("登陆", forState: UIControlState.Normal)
//设置文本颜色
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
//设置文本大小
btn.titleLabel?.font = UIFont.systemFontOfSize(14)
//根据内容适应大小
btn.sizeToFit()
btn.addTarget(self, action: "loginClick", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
/// 懒加载 注册按钮
private lazy var registerBtn: UIButton = {
//实例化
let btn = UIButton()
//设置按钮的背景图片
btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
//设置文字
btn.setTitle("注册", forState: UIControlState.Normal)
//设置文本颜色
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
//设置文本大小
btn.titleLabel?.font = UIFont.systemFontOfSize(14)
//根据内容适应大小
btn.sizeToFit()
btn.addTarget(self, action: "vistorViewRegisterClick", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
/// 懒加载 遮罩 图片
private lazy var converView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
}
|
apache-2.0
|
ddd043edb4a23b359329efa88a84170c
| 43.49569 | 225 | 0.681682 | 4.792479 | false | false | false | false |
dimpiax/StyleDecorator
|
Sources/StyleDecorator/Style.swift
|
1
|
5764
|
//
// Style.swift
// StyleDecorator
//
// Created by Dmytro Pylypenko on 11/10/19.
//
import Foundation
import UIKit
/// Style class for easy text view attributes setup
final public class Style {
/// Dictionary with native attributes
public fileprivate(set) var attributes: [NSAttributedString.Key: Any]! = [:]
fileprivate var _paragraphStyle: NSMutableParagraphStyle?
/// Empty initializer
public init() {}
/**
Set font. If you do not specify this attribute, the string uses a 12-point Helvetica(Neue) font by default.
- Parameter value: exist font. Example: UIFont.systemFont(ofSize: 17)
*/
public func font(_ value: UIFont) -> Self {
attributes[.font] = value
return self
}
/**
The value of this attribute is an NSParagraphStyle object.
*/
public func paragraphStyle(_ value: NSMutableParagraphStyle) -> Self {
_paragraphStyle = value
attributes[.paragraphStyle] = value
return self
}
/**
The value of this attribute is a UIColor object. Use this attribute to specify the color of the text during rendering. If you do not specify this attribute, the text is rendered in black.
*/
public func foregroundColor(_ value: UIColor?) -> Self {
attributes[.foregroundColor] = value
return self
}
/**
The value of this attribute is a UIColor object. Use this attribute to specify the color of the background area behind the text. If you do not specify this attribute, no background color is dattributesn.
*/
public func backgroundColor(_ value: UIColor?) -> Self {
attributes[.backgroundColor] = value
return self
}
/**
Set ligature
- Parameter value: ligature style. default is 1 – default ligatures, 0 – no ligatures
*/
public func ligature(_ value: Int) -> Self {
attributes[.ligature] = value
return self
}
/**
Set kerning
- Parameter value: in points; amount to modify default kerning. 0 means kerning is disabled.
*/
public func kerning(_ value: CGFloat) -> Self {
attributes[.kern] = value
return self
}
/**
Set strikethrough
- Parameter value: strikethrough style. 0 – no strikethrough
*/
public func strikethroughStyle(_ value: Int) -> Self {
attributes[.strikethroughStyle] = value
return self
}
/**
Set underline style
- Parameter value: underline style. 0 – no underline
*/
public func underlineStyle(_ value: Int) -> Self {
attributes[.underlineStyle] = value
return self
}
/**
Set stroke color
- Parameter value: stroke color
*/
public func strokeColor(_ value: UIColor?) -> Self {
attributes[.strokeColor] = value
return self
}
/**
Set stroke width
- Parameter value: in percent of font point size. 0 – no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0)
*/
public func strokeWidth(_ value: CGFloat) -> Self {
attributes[.strokeWidth] = value
return self
}
/**
Set shadow
- Parameter value: shadow text
*/
public func shadow(_ value: NSShadow?) -> Self {
attributes[.shadow] = value
return self
}
/**
Set text effect
- Parameter value: text effect
*/
public func textEffect(_ value: String?) -> Self {
attributes[.textEffect] = value
return self
}
/**
Set attachment
- Parameter value: attachment in text
*/
public func attachment(_ value: NSTextAttachment?) -> Self {
attributes[.attachment] = value
return self
}
/**
Set link
- Parameter value: URL for link
*/
public func link(_ value: URL?) -> Self {
attributes[.link] = value
return self
}
/**
Set baseline offset
- Parameter value: offset from baseline in points
*/
public func baselineOffset(_ value: CGFloat) -> Self {
attributes[.baselineOffset] = value
return self
}
/**
Set underline color
- Parameter value: underline color
*/
public func underlineColor(_ value: UIColor?) -> Self {
attributes[.underlineColor] = value
return self
}
/**
Set strikethrough color
- Parameter value: strikethrough color
*/
public func strikethroughColor(_ value: UIColor?) -> Self {
attributes[.strikethroughColor] = value
return self
}
/**
Set obliqueness
- Parameter value: skew to be applied to glyphs
*/
public func obliqueness(_ value: CGFloat) -> Self {
attributes[.obliqueness] = value
return self
}
/**
Set expansion factor
- Parameter value: expansion factor to be applied to glyphs. 0 – no expansion
*/
public func expansion(_ value: CGFloat) -> Self {
attributes[.expansion] = value
return self
}
// ???
/*public func writingDirection(_ value: [CGFloat]) -> Self {
attributes[NSWritingDirectionAttributeName] = value
return self
}*/
/**
Set vertical glyph form
- Parameter value: The value 0 indicates horizontal text. The value 1 indicates vertical text.
*/
public func verticalGlyphForm(_ value: Int) -> Self {
attributes[.verticalGlyphForm] = value
return self
}
/**
Set text alignment, it can be one of:
* left
* center
* right
* justified
* natural
It will overwrite your custom paragraph which has been set in `paragraphStyle` method
- Parameter value: text alignment enum
- Returns: Same Attributes instance for chain calling
*/
public func alignment(_ value: NSTextAlignment) -> Self {
let p = NSMutableParagraphStyle()
p.alignment = value
return paragraphStyle(p)
}
deinit {
attributes = nil
_paragraphStyle = nil
}
}
|
mit
|
3d455936ca7d77c5504fe8baf3e31a65
| 22.382114 | 206 | 0.650556 | 4.710893 | false | false | false | false |
Hout/SwiftDate
|
Sources/SwiftDate/Foundation+Extras/TimeInterval+Formatter.swift
|
2
|
6758
|
//
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
public extension TimeInterval {
struct ComponentsFormatterOptions {
/// Fractional units may be used when a value cannot be exactly represented using the available units.
/// For example, if minutes are not allowed, the value “1h 30m” could be formatted as “1.5h”.
public var allowsFractionalUnits: Bool?
/// Specify the units that can be used in the output.
public var allowedUnits: NSCalendar.Unit?
/// A Boolean value indicating whether to collapse the largest unit into smaller units when a certain threshold is met.
public var collapsesLargestUnit: Bool?
/// The maximum number of time units to include in the output string.
/// If 0 does not cause the elimination of any units.
public var maximumUnitCount: Int?
/// The formatting style for units whose value is 0.
public var zeroFormattingBehavior: DateComponentsFormatter.ZeroFormattingBehavior?
/// The preferred style for units.
public var unitsStyle: DateComponentsFormatter.UnitsStyle?
/// Locale of the formatter
public var locale: LocaleConvertible? {
set { calendar.locale = newValue?.toLocale() }
get { return calendar.locale }
}
/// Calendar
public var calendar = Calendar.autoupdatingCurrent
public func apply(toFormatter formatter: DateComponentsFormatter) {
formatter.calendar = calendar
if let allowsFractionalUnits = self.allowsFractionalUnits {
formatter.allowsFractionalUnits = allowsFractionalUnits
}
if let allowedUnits = self.allowedUnits {
formatter.allowedUnits = allowedUnits
}
if let collapsesLargestUnit = self.collapsesLargestUnit {
formatter.collapsesLargestUnit = collapsesLargestUnit
}
if let maximumUnitCount = self.maximumUnitCount {
formatter.maximumUnitCount = maximumUnitCount
}
if let zeroFormattingBehavior = self.zeroFormattingBehavior {
formatter.zeroFormattingBehavior = zeroFormattingBehavior
}
if let unitsStyle = self.unitsStyle {
formatter.unitsStyle = unitsStyle
}
}
public init() {}
}
/// Return the local thread shared formatter for date components
private static func sharedFormatter() -> DateComponentsFormatter {
let name = "SwiftDate_\(NSStringFromClass(DateComponentsFormatter.self))"
return threadSharedObject(key: name, create: {
let formatter = DateComponentsFormatter()
formatter.includesApproximationPhrase = false
formatter.includesTimeRemainingPhrase = false
return formatter
})
}
//@available(*, deprecated: 5.0.13, obsoleted: 5.1, message: "Use toIntervalString function instead")
func toString(options callback: ((inout ComponentsFormatterOptions) -> Void)? = nil) -> String {
return self.toIntervalString(options: callback)
}
/// Format a time interval in a string with desidered components with passed style.
///
/// - Parameters:
/// - units: units to include in string.
/// - style: style of the units, by default is `.abbreviated`
/// - Returns: string representation
func toIntervalString(options callback: ((inout ComponentsFormatterOptions) -> Void)? = nil) -> String {
let formatter = DateComponentsFormatter()
var options = ComponentsFormatterOptions()
callback?(&options)
options.apply(toFormatter: formatter)
let formattedValue = (formatter.string(from: self) ?? "")
if options.zeroFormattingBehavior?.contains(.pad) ?? false {
// for some strange reason padding is not added at the very beginning positional item.
// we'll add it manually if necessaru
if let index = formattedValue.firstIndex(of: ":"), index.utf16Offset(in: formattedValue) < 2 {
return "0\(formattedValue)"
}
}
return formattedValue
}
/// Format a time interval in a string with desidered components with passed style.
///
/// - Parameter options: options for formatting.
/// - Returns: string representation
func toString(options: ComponentsFormatterOptions) -> String {
let formatter = TimeInterval.sharedFormatter()
options.apply(toFormatter: formatter)
return (formatter.string(from: self) ?? "")
}
/// Return a string representation of the time interval in form of clock countdown (ie. 57:00:00)
///
/// - Parameter zero: behaviour with zero.
/// - Returns: string representation
func toClock(zero: DateComponentsFormatter.ZeroFormattingBehavior = [.pad, .dropLeading]) -> String {
return toIntervalString(options: {
$0.collapsesLargestUnit = true
$0.maximumUnitCount = 0
$0.unitsStyle = .positional
$0.locale = Locales.englishUnitedStatesComputer
$0.zeroFormattingBehavior = zero
})
}
/// Extract requeste time units components from given interval.
/// Reference date's calendar is used to make the extraction.
///
/// NOTE:
/// Extraction is calendar/date based; if you specify a `refDate` calculation is made
/// between the `refDate` and `refDate + interval`.
/// If `refDate` is `nil` evaluation is made from `now()` and `now() + interval` in the context
/// of the `SwiftDate.defaultRegion` set.
///
/// - Parameters:
/// - units: units to extract
/// - from: starting reference date, `nil` means `now()` in the context of the default region set.
/// - Returns: dictionary with extracted components
func toUnits(_ units: Set<Calendar.Component>, to refDate: DateInRegion? = nil) -> [Calendar.Component: Int] {
let dateTo = (refDate ?? DateInRegion())
let dateFrom = dateTo.addingTimeInterval(-self)
let components = dateFrom.calendar.dateComponents(units, from: dateFrom.date, to: dateTo.date)
return components.toDict()
}
/// Express a time interval (expressed in seconds) in another time unit you choose.
/// Reference date's calendar is used to make the extraction.
///
/// - parameter component: time unit in which you want to express the calendar component
/// - parameter from: starting reference date, `nil` means `now()` in the context of the default region set.
///
/// - returns: the value of interval expressed in selected `Calendar.Component`
func toUnit(_ component: Calendar.Component, to refDate: DateInRegion? = nil) -> Int? {
return toUnits([component], to: refDate)[component]
}
}
|
mit
|
98acaaf1612fc592200674b21ffb6426
| 39.172619 | 121 | 0.698474 | 4.416885 | false | false | false | false |
lixiangzhou/ZZKG
|
ZZKG/ZZKG/Classes/Lib/ZZLib/ZZCustom/ZZRefresh/ZZRefresh.swift
|
1
|
1028
|
//
// ZZRefresh.swift
// ZZRefresh
//
// Created by lixiangzhou on 16/10/26.
// Copyright © 2016年 lixiangzhou. All rights reserved.
//
import UIKit
let zz_RefreshConstant = ZZRefreshConstant()
struct ZZRefreshConstant {
let headerHeight: CGFloat = 50
let footerHeight: CGFloat = 40
let headerNormalText = "下拉即将刷新..."
let headerReleaseText = "松开立即刷新..."
let headerRefreshingText = "正在刷新..."
let footerNormalText = "上拉即将刷新..."
let footerReleaseText = "松开立即刷新..."
let footerRefreshingText = "正在刷新..."
let headerRefreshDuration = 0.3
let footerRefreshDuration = 0.3
}
enum ZZRefreshState {
case normal // 正常状态
case willRefreshing // 即将刷新的状态
case releaseRefreshing // 释放即可刷新的状态
case refreshing // 正在刷新状态
}
enum ZZRefreshViewPositionStyle {
case bottom
case top
case scaleToFill
}
|
mit
|
06e8a10483cc4e721228cc59640a3166
| 21.170732 | 55 | 0.647965 | 3.901288 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Models/CoreData/Game Rows/GameNotes.swift
|
1
|
4285
|
//
// GameNotes.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/19/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
extension Note: CodableCoreDataStorable {
/// (CodableCoreDataStorable Protocol)
/// Type of the core data entity.
public typealias EntityType = GameNotes
/// (CodableCoreDataStorable Protocol)
/// Sets core data values to match struct values (specific).
public func setAdditionalColumnsOnSave(
coreItem: EntityType
) {
setDateModifiableColumnsOnSave(coreItem: coreItem) //TODO
coreItem.uuid = uuid.uuidString
coreItem.gameSequenceUuid = gameSequenceUuid?.uuidString
coreItem.gameVersion = gameVersion.stringValue
coreItem.shepardUuid = shepardUuid?.uuidString
coreItem.identifyingObject = identifyingObject.flattenedString
coreItem.isSavedToCloud = isSavedToCloud ? 1 : 0
}
/// (CodableCoreDataStorable Protocol)
/// Alters the predicate to retrieve only the row equal to this object.
public func setIdentifyingPredicate(
fetchRequest: NSFetchRequest<EntityType>
) {
fetchRequest.predicate = NSPredicate(
format: "(%K == %@)",
#keyPath(GameNotes.uuid), uuid.uuidString
)
}
}
extension Note {
// MARK: Save
public mutating func saveAnyChanges(
with manager: CodableCoreDataManageable?
) -> Bool {
if hasUnsavedChanges {
let isSaved = save(with: manager)
return isSaved
}
return true
}
public mutating func saveAnyChanges() -> Bool {
return saveAnyChanges(with: nil)
}
public mutating func save( // override to mark game sequence changed also
with manager: CodableCoreDataManageable?
) -> Bool {
let manager = manager ?? defaultManager
let isSaved = manager.saveValue(item: self)
if isSaved {
hasUnsavedChanges = false
if App.current.game?.uuid == gameSequenceUuid {
markGameChanged(with: manager)
}
}
return isSaved
}
// MARK: Delete
public static func delete(
uuid: UUID,
gameSequenceUuid: UUID,
with manager: CodableCoreDataManageable? = nil
) -> Bool {
if !GamesDataBackup.current.isSyncing {
// save record for CloudKit
notifyDeleteToCloud(uuid: uuid, gameSequenceUuid: gameSequenceUuid, with: manager)
}
return deleteAll(with: manager) { fetchRequest in
fetchRequest.predicate = NSPredicate(
format: "(%K == %@)",
#keyPath(GameNotes.uuid), uuid.uuidString
)
}
}
/// Stores a row before delete
public static func notifyDeleteToCloud(
uuid: UUID,
gameSequenceUuid: UUID,
with manager: CodableCoreDataManageable? = nil
) {
let deletedRows: [DeletedRow] = [DeletedRow(
source: Note.entityName,
identifier: getIdentifyingName(id: uuid.uuidString, gameSequenceUuid: gameSequenceUuid)
)]
_ = DeletedRow.saveAll(items: deletedRows, with: manager)
GamesDataBackup.current.isPendingCloudChanges = true
}
/// Only called by GameSequence. This does not notify cloud or cascade delete, so do not call it in other places.
public static func deleteAll(
gameSequenceUuid: UUID,
with manager: CodableCoreDataManageable? = nil
) -> Bool {
// don't have to notify: GameSequence did that for you
return deleteAll(with: manager) { fetchRequest in
fetchRequest.predicate = NSPredicate(
format: "(%K == %@)",
#keyPath(GameNotes.gameSequenceUuid), gameSequenceUuid.uuidString
)
}
}
// MARK: Additional Convenience Gets
public static func get(
uuid: UUID,
with manager: CodableCoreDataManageable? = nil
) -> Note? {
return get(with: manager) { fetchRequest in
fetchRequest.predicate = NSPredicate(
format: "(%K == %@)",
#keyPath(GameNotes.uuid), uuid.uuidString
)
}
}
public static func getAll(
uuids: [UUID],
with manager: CodableCoreDataManageable? = nil
) -> [Note] {
return getAll(with: manager) { fetchRequest in
fetchRequest.predicate = NSPredicate(
format: "(%K in %@)",
#keyPath(GameNotes.uuid), uuids.map { $0.uuidString }
)
}
}
public static func getAll(
identifyingObject: IdentifyingObject,
with manager: CodableCoreDataManageable? = nil
) -> [Note] {
return getAll(with: manager) { fetchRequest in
fetchRequest.predicate = NSPredicate(
format: "(%K == %@)",
#keyPath(GameNotes.identifyingObject), identifyingObject.flattenedString
)
}
}
}
|
mit
|
2acca15ba1465101e224ff1787d005fa
| 25.608696 | 114 | 0.71732 | 3.908759 | false | false | false | false |
mleiv/MEGameTracker
|
MEGameTracker/Models/CloudKit/CloudKit Records/CloudKitEvents.swift
|
1
|
939
|
//
// GameEvents.swift
// MEGameTracker
//
// Created by Emily Ivie on 12/31/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import Foundation
import CloudKit
extension Event: CloudDataStorable {
/// (CloudDataStorable)
/// Set any additional fields, specific to the object in question, for a cloud kit object.
public func setAdditionalCloudFields(record: CKRecord) {
record.setValue(isTriggered as NSNumber, forKey: "isTriggered")
}
/// (CloudDataStorable Protocol)
/// Alter any CK items before handing to codable to modify/create object
public func getAdditionalCloudFields(changeRecord: CloudDataRecordChange) -> [String: Any?] {
var changes = changeRecord.changeSet
changes["isTriggered"] = (changes["isTriggered"] as? Int == 1) || (changes["isTriggered"] as? Double == 1)
// changes.removeValue(forKey: "lastRecordData")
return changes
}
}
|
mit
|
86ff00a9f52a6480fcc9871b1aeb12d3
| 32.5 | 114 | 0.691898 | 4.445498 | false | false | false | false |
jtbandes/swift
|
benchmark/single-source/ArrayOfPOD.swift
|
21
|
1420
|
//===--- ArrayOfPOD.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This benchmark tests creation and destruction of an array of
// trivial static type. It is meant to be a baseline for comparison against
// ArrayOfGenericPOD.
//
// For comparison, we always create three arrays of 200,000 words.
class RefArray<T> {
var array : [T]
init(_ i:T, count:Int = 100_000) {
array = [T](repeating: i, count: count)
}
}
@inline(never)
func genIntArray() {
_ = RefArray<Int>(3, count:200_000)
// should be a nop
}
enum PODEnum {
case Some(Int)
init(i:Int) { self = .Some(i) }
}
@inline(never)
func genEnumArray() {
_ = RefArray<PODEnum>(PODEnum.Some(3))
// should be a nop
}
struct S {
var x: Int
var y: Int
}
@inline(never)
func genStructArray() {
_ = RefArray<S>(S(x:3, y:4))
// should be a nop
}
@inline(never)
public func run_ArrayOfPOD(_ N: Int) {
for _ in 0...N {
genIntArray()
genEnumArray()
genStructArray()
}
}
|
apache-2.0
|
930e9861045882efc1cfcc6699d61181
| 21.903226 | 80 | 0.6 | 3.514851 | false | false | false | false |
aronse/Hero
|
Sources/HeroContext.swift
|
1
|
12357
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class HeroContext {
internal var heroIDToSourceView = [String: UIView]()
internal var heroIDToDestinationView = [String: UIView]()
internal var snapshotViews = [UIView: UIView]()
internal var viewAlphas = [UIView: CGFloat]()
internal var targetStates = [UIView: HeroTargetState]()
internal var superviewToNoSnapshotSubviewMap: [UIView: [(Int, UIView)]] = [:]
internal var insertToViewFirst = false
internal var defaultCoordinateSpace: HeroCoordinateSpace = .local
internal init(container: UIView) {
self.container = container
}
internal func set(fromViews: [UIView], toViews: [UIView]) {
self.fromViews = fromViews
self.toViews = toViews
process(views: fromViews, idMap: &heroIDToSourceView)
process(views: toViews, idMap: &heroIDToDestinationView)
}
internal func process(views: [UIView], idMap: inout [String: UIView]) {
for view in views {
view.layer.removeAllAnimations()
let targetState: HeroTargetState?
if let modifiers = view.heroModifiers {
targetState = HeroTargetState(modifiers: modifiers)
} else {
targetState = nil
}
if targetState?.forceAnimate == true || container.convert(view.bounds, from: view).intersects(container.bounds) {
if let heroID = view.heroID {
idMap[heroID] = view
}
targetStates[view] = targetState
}
}
}
/**
The container holding all of the animating views
*/
public let container: UIView
/**
A flattened list of all views from source ViewController
*/
public var fromViews: [UIView] = []
/**
A flattened list of all views from destination ViewController
*/
public var toViews: [UIView] = []
}
// public
extension HeroContext {
/**
- Returns: a source view matching the heroID, nil if not found
*/
public func sourceView(for heroID: String) -> UIView? {
return heroIDToSourceView[heroID]
}
/**
- Returns: a destination view matching the heroID, nil if not found
*/
public func destinationView(for heroID: String) -> UIView? {
return heroIDToDestinationView[heroID]
}
/**
- Returns: a view with the same heroID, but on different view controller, nil if not found
*/
public func pairedView(for view: UIView) -> UIView? {
if let id = view.heroID {
if sourceView(for: id) == view {
return destinationView(for: id)
} else if destinationView(for: id) == view {
return sourceView(for: id)
}
}
return nil
}
/**
- Returns: a snapshot view for animation
*/
public func snapshotView(for view: UIView) -> UIView {
if let snapshot = snapshotViews[view] {
return snapshot
}
var containerView = container
let coordinateSpace = targetStates[view]?.coordinateSpace ?? defaultCoordinateSpace
switch coordinateSpace {
case .local:
containerView = view
while containerView != container, snapshotViews[containerView] == nil, let superview = containerView.superview {
containerView = superview
}
if let snapshot = snapshotViews[containerView] {
containerView = snapshot
}
if let visualEffectView = containerView as? UIVisualEffectView {
containerView = visualEffectView.contentView
}
case .global:
break
}
unhide(view: view)
// capture a snapshot without alpha & cornerRadius
let oldCornerRadius = view.layer.cornerRadius
let oldAlpha = view.alpha
view.layer.cornerRadius = 0
view.alpha = 1
let snapshot: UIView
let snapshotType: HeroSnapshotType = self[view]?.snapshotType ?? .optimized
switch snapshotType {
case .normal:
snapshot = view.snapshotView() ?? UIView()
case .layerRender:
snapshot = view.slowSnapshotView()
case .noSnapshot:
if view.superview != container {
if superviewToNoSnapshotSubviewMap[view.superview!] == nil {
superviewToNoSnapshotSubviewMap[view.superview!] = []
}
superviewToNoSnapshotSubviewMap[view.superview!]!.append((view.superview!.subviews.index(of: view)!, view))
}
snapshot = view
case .optimized:
#if os(tvOS)
snapshot = view.snapshotView(afterScreenUpdates: true)!
#else
if #available(iOS 9.0, *), let stackView = view as? UIStackView {
snapshot = stackView.slowSnapshotView()
} else if let imageView = view as? UIImageView, view.subviews.isEmpty {
let contentView = UIImageView(image: imageView.image)
contentView.frame = imageView.bounds
contentView.contentMode = imageView.contentMode
contentView.tintColor = imageView.tintColor
contentView.backgroundColor = imageView.backgroundColor
let snapShotView = UIView()
snapShotView.addSubview(contentView)
snapshot = snapShotView
} else if let barView = view as? UINavigationBar, barView.isTranslucent {
let newBarView = UINavigationBar(frame: barView.frame)
newBarView.barStyle = barView.barStyle
newBarView.tintColor = barView.tintColor
newBarView.barTintColor = barView.barTintColor
newBarView.clipsToBounds = false
// take a snapshot without the background
barView.layer.sublayers![0].opacity = 0
let realSnapshot = barView.snapshotView(afterScreenUpdates: true)!
barView.layer.sublayers![0].opacity = 1
newBarView.addSubview(realSnapshot)
snapshot = newBarView
} else if let effectView = view as? UIVisualEffectView {
snapshot = UIVisualEffectView(effect: effectView.effect)
snapshot.frame = effectView.bounds
} else {
snapshot = view.snapshotView() ?? UIView()
}
#endif
}
#if os(tvOS)
if let imageView = view as? UIImageView, imageView.adjustsImageWhenAncestorFocused {
snapshot.frame = imageView.focusedFrameGuide.layoutFrame
}
#endif
view.layer.cornerRadius = oldCornerRadius
view.alpha = oldAlpha
snapshot.layer.anchorPoint = view.layer.anchorPoint
snapshot.layer.position = containerView.convert(view.layer.position, from: view.superview!)
snapshot.layer.transform = containerView.layer.flatTransformTo(layer: view.layer)
snapshot.layer.bounds = view.layer.bounds
snapshot.heroID = view.heroID
if snapshotType != .noSnapshot {
if !(view is UINavigationBar), let contentView = snapshot.subviews.get(0) {
// the Snapshot's contentView must have hold the cornerRadius value,
// since the snapshot might not have maskToBounds set
contentView.layer.cornerRadius = view.layer.cornerRadius
contentView.layer.masksToBounds = true
}
snapshot.layer.allowsGroupOpacity = false
snapshot.layer.cornerRadius = view.layer.cornerRadius
snapshot.layer.zPosition = view.layer.zPosition
snapshot.layer.opacity = view.layer.opacity
snapshot.layer.isOpaque = view.layer.isOpaque
snapshot.layer.anchorPoint = view.layer.anchorPoint
snapshot.layer.masksToBounds = view.layer.masksToBounds
snapshot.layer.borderColor = view.layer.borderColor
snapshot.layer.borderWidth = view.layer.borderWidth
snapshot.layer.contentsRect = view.layer.contentsRect
snapshot.layer.contentsScale = view.layer.contentsScale
if self[view]?.displayShadow ?? true {
snapshot.layer.shadowRadius = view.layer.shadowRadius
snapshot.layer.shadowOpacity = view.layer.shadowOpacity
snapshot.layer.shadowColor = view.layer.shadowColor
snapshot.layer.shadowOffset = view.layer.shadowOffset
snapshot.layer.shadowPath = view.layer.shadowPath
}
hide(view: view)
}
if let pairedView = pairedView(for: view), let pairedSnapshot = snapshotViews[pairedView] {
let siblingViews = pairedView.superview!.subviews
let nextSiblings = siblingViews[siblingViews.index(of: pairedView)!+1..<siblingViews.count]
containerView.addSubview(pairedSnapshot)
containerView.addSubview(snapshot)
for subview in pairedView.subviews {
insertGlobalViewTree(view: subview)
}
for sibling in nextSiblings {
insertGlobalViewTree(view: sibling)
}
} else {
containerView.addSubview(snapshot)
}
containerView.addSubview(snapshot)
snapshotViews[view] = snapshot
return snapshot
}
func insertGlobalViewTree(view: UIView) {
if targetStates[view]?.coordinateSpace == .global, let snapshot = snapshotViews[view] {
container.addSubview(snapshot)
}
for subview in view.subviews {
insertGlobalViewTree(view: subview)
}
}
public subscript(view: UIView) -> HeroTargetState? {
get {
return targetStates[view]
}
set {
targetStates[view] = newValue
}
}
public func clean() {
for (superview, subviews) in superviewToNoSnapshotSubviewMap {
for (index, view) in subviews.reversed() {
superview.insertSubview(view, at: index)
}
}
}
}
// internal
extension HeroContext {
public func hide(view: UIView) {
if viewAlphas[view] == nil {
if view is UIVisualEffectView {
view.isHidden = true
viewAlphas[view] = 1
} else {
viewAlphas[view] = view.alpha
view.alpha = 0
}
}
}
public func unhide(view: UIView) {
if let oldAlpha = viewAlphas[view] {
if view is UIVisualEffectView {
view.isHidden = false
} else {
view.alpha = oldAlpha
}
viewAlphas[view] = nil
}
}
internal func unhideAll() {
for view in viewAlphas.keys {
unhide(view: view)
}
viewAlphas.removeAll()
}
internal func unhide(rootView: UIView) {
unhide(view: rootView)
for subview in rootView.subviews {
unhide(rootView: subview)
}
}
internal func removeAllSnapshots() {
for (view, snapshot) in snapshotViews {
if view != snapshot {
snapshot.removeFromSuperview()
} else {
view.layer.removeAllAnimations()
}
}
}
internal func removeSnapshots(rootView: UIView) {
if let snapshot = snapshotViews[rootView] {
if rootView != snapshot {
snapshot.removeFromSuperview()
} else {
rootView.layer.removeAllAnimations()
}
}
for subview in rootView.subviews {
removeSnapshots(rootView: subview)
}
}
internal func snapshots(rootView: UIView) -> [UIView] {
var snapshots = [UIView]()
for v in rootView.flattenedViewHierarchy {
if let snapshot = snapshotViews[v] {
snapshots.append(snapshot)
}
}
return snapshots
}
internal func loadViewAlpha(rootView: UIView) {
if let storedAlpha = rootView.heroStoredAlpha {
rootView.alpha = storedAlpha
rootView.heroStoredAlpha = nil
}
for subview in rootView.subviews {
loadViewAlpha(rootView: subview)
}
}
internal func storeViewAlpha(rootView: UIView) {
rootView.heroStoredAlpha = viewAlphas[rootView]
for subview in rootView.subviews {
storeViewAlpha(rootView: subview)
}
}
}
|
mit
|
f7354ff922cef1c203c593d21c62f166
| 31.952 | 119 | 0.676378 | 4.617713 | false | false | false | false |
dogo/AKSideMenu
|
AKSideMenuExamples/Simple/AKSideMenuSimple/RightMenuViewController/RightMenuViewController.swift
|
1
|
1326
|
//
// RightMenuViewController.swift
// AKSideMenuSimple
//
// Created by Diogo Autilio on 6/7/16.
// Copyright © 2016 AnyKey Entertainment. All rights reserved.
//
import AKSideMenu
import UIKit
final class RightMenuViewController: UIViewController {
// MARK: - Properties
let rightMenuView = RightMenuView()
// MARK: - Life Cycle
override func loadView() {
view = rightMenuView
}
override func viewDidLoad() {
super.viewDidLoad()
rightMenuView.didTouchIndex = { [weak self] index in
self?.handleTouch(at: index)
}
}
// MARK: - Actions
private func handleTouch(at index: Int) {
switch index {
case 0:
let contentViewController = UINavigationController(rootViewController: FirstViewController())
self.sideMenuViewController?.setContentViewController(contentViewController, animated: true)
self.sideMenuViewController?.hideMenuViewController()
case 1:
let contentViewController = UINavigationController(rootViewController: SecondViewController())
sideMenuViewController?.setContentViewController(contentViewController, animated: true)
sideMenuViewController?.hideMenuViewController()
default:
break
}
}
}
|
mit
|
eb7661ff309f12e9b55e1c8de68d4408
| 26.604167 | 106 | 0.670189 | 5.567227 | false | false | false | false |
ZackKingS/Tasks
|
task/Classes/Others/Lib/LLCycleScrollView/LLCycleScrollViewCell.swift
|
2
|
3296
|
//
// LLCycleScrollViewCell.swift
// LLCycleScrollView
//
// Created by LvJianfeng on 2016/11/22.
// Copyright © 2016年 LvJianfeng. All rights reserved.
//
import UIKit
class LLCycleScrollViewCell: UICollectionViewCell {
// 标题
var title: String = "" {
didSet {
titleLabel.text = "\(title)"
if title.characters.count > 0 {
titleBackView.isHidden = false
titleLabel.isHidden = false
}else{
titleBackView.isHidden = true
titleLabel.isHidden = true
}
}
}
// 标题颜色
var titleLabelTextColor: UIColor = UIColor.white {
didSet {
titleLabel.textColor = titleLabelTextColor
}
}
// 标题字体
var titleFont: UIFont = UIFont.systemFont(ofSize: 15) {
didSet {
titleLabel.font = titleFont
}
}
// 文本行数
var titleLines: NSInteger = 2 {
didSet {
titleLabel.numberOfLines = titleLines
}
}
// 标题文本x轴间距
var titleLabelLeading: CGFloat = 15 {
didSet {
setNeedsDisplay()
}
}
// 标题背景色
var titleBackViewBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.3) {
didSet {
titleBackView.backgroundColor = titleBackViewBackgroundColor
}
}
var titleBackView: UIView!
// 标题Label高度
var titleLabelHeight: CGFloat! = 56 {
didSet {
layoutSubviews()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupImageView()
setupLabelBackView()
setupTitleLabel()
}
// 图片
var imageView: UIImageView!
fileprivate var titleLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Setup ImageView
fileprivate func setupImageView() {
imageView = UIImageView.init()
// 默认模式
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
self.contentView.addSubview(imageView)
}
// Setup Label BackView
fileprivate func setupLabelBackView() {
titleBackView = UIView.init()
titleBackView.backgroundColor = titleBackViewBackgroundColor
self.contentView.addSubview(titleBackView)
}
// Setup Title
fileprivate func setupTitleLabel() {
titleLabel = UILabel.init()
titleLabel.isHidden = true
titleLabel.textColor = titleLabelTextColor
titleLabel.numberOfLines = titleLines
titleLabel.font = titleFont
titleLabel.backgroundColor = UIColor.clear
titleBackView.addSubview(titleLabel)
}
// MARK: layoutSubviews
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
titleBackView.frame = CGRect.init(x: 0, y: self.ll_h - titleLabelHeight, width: self.ll_w, height: titleLabelHeight)
titleLabel.frame = CGRect.init(x: titleLabelLeading, y: 0, width: self.ll_w - titleLabelLeading - 5, height: titleLabelHeight)
}
}
|
apache-2.0
|
f276941d523c6276e8f20698bb4f43b5
| 25.186992 | 134 | 0.592363 | 5.096519 | false | false | false | false |
hq7781/MoneyBook
|
MoneyBook/Controller/Setting/SettingViewController.swift
|
1
|
10957
|
//
// SettingViewController.swift
// MoneyBook
//
// Created by HongQuan on 2017/04/30.
// Copyright © 2017年 Roan.Hong. All rights reserved.
//
import UIKit
//import AdSupport
import GoogleMobileAds
class SettingViewController: UIViewController {
fileprivate lazy var images: NSMutableArray! = {
var array = NSMutableArray(array: ["about","score","recommend","feedback","removecache", "purchase", "verinfo"])
return array
}()
fileprivate lazy var titles: NSMutableArray! = {
var array = NSMutableArray(array: ["about","score","recommend","feedback","removecache", "purchase", "verinfo"])
return array
}()
fileprivate var tableView: UITableView!
//
var cityButton: TextImageButton!
var mapButton: TextImageButton!
var buttonB: UIView!
var someView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupUI()
AppUtils.googleTracking("SettingView")
showAdBannerView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector:#selector(onCityChange), name:kNotificationNameCurrentCityhasChanged, object:nil)
NotificationCenter.default.removeObserver(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// self.view.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
required init?(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
super.init(coder: aDecoder)
//接受通知监听
NotificationCenter.default.addObserver(self, selector:#selector(onCityChange), name:kNotificationNameCurrentCityhasChanged, object:nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
print("SettingViewController has destroyed", terminator: "")
}
/*
// 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.
}
*/
func setupUI() {
//self.view.backgroundColor = UIColor.brown // UIColor.enixGreen()
self.navigationItem.title = "Setting"
// Setting Table List
self.setTableViewUI()
//self.showEasyTipViewUI()
self.showUserVistCountInfoUI()
self.showCityChangeUI()
self.showMapViewUI()
}
func setTableViewUI() {
tableView = UITableView(frame:view.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
//tableView.backgroundColor = UIColor.yellow // UIColor.enixColorWith(247, 247, 247, alpha: 1)
tableView.rowHeight = 50
tableView.separatorStyle = .none
tableView.register(UINib(nibName:"SettingCell", bundle:nil), forCellReuseIdentifier: "settingCell")
view.addSubview(tableView)
}
func showEasyTipViewUI() {
buttonB = UIView(frame: CGRectMake(30, 30, 50, 35))
//buttonB = UIButton(frame: CGRectMake(0, 30, 50, 35))
//buttonB.setTitle(title: "buttonB", state: UIControlState.normal)
buttonB.backgroundColor = UIColor.red
self.view.addSubview(buttonB)
someView = UIView(frame: CGRectMake(30, 200, 300, 60))
someView.backgroundColor = UIColor.yellow
self.view.addSubview(someView)
var preferences = EasyTipView.Preferences()
preferences.animating.dismissDuration = 6.0
preferences.drawing.font = UIFont(name: "Futura-Medium", size: 13)!
preferences.drawing.foregroundColor = UIColor.white
preferences.drawing.backgroundColor = UIColor(hue:0.46, saturation:0.99, brightness:0.6, alpha:1)
preferences.drawing.arrowPosition = EasyTipView.ArrowPosition.top
EasyTipView.globalPreferences = preferences
EasyTipView.show(forView: self.buttonB,
withinSuperview: self.navigationController?.view,
text: "Tip view inside the navigation controller's view. Tap to dismiss!",
preferences: preferences,
delegate: self as? EasyTipViewDelegate)
let tipView = EasyTipView(text: "Some text...........", preferences: preferences)
tipView.show(forView: self.someView, withinSuperview: self.navigationController?.view)
// later on you can dismiss it
tipView.dismiss()
}
//MARK: - ========== easyTipViewDelegate ==========
func easyTipViewDidDismiss(_ easyTipView : EasyTipView) {
print("easyTipViewDidDismiss")
}
func showUserVistCountInfoUI() {
let visitCount: Int = AppUtils.getVisitCount()!
let myLabel:UILabel = UILabel()
myLabel.text = "Visited Count:\(visitCount)"
_ = AppUtils.setVisiCount()
myLabel.sizeToFit()
myLabel.center = CGPoint(x:self.view.frame.width/2, y: self.view.frame.height/2 + 100)
self.view.addSubview(myLabel)
}
func showCityChangeUI() {
cityButton = TextImageButton(frame: CGRect.CGRectMake(40, 300, 80, 44))
if let currentCity = AppUtils.getSelectedCity() as String? {
cityButton.setTitle(currentCity, for: .normal)
} else {
cityButton.setTitle("tokyo", for: .normal)
}
cityButton.titleLabel?.font = theme.appNaviItemFont
cityButton.setTitleColor(UIColor.black, for: UIControlState.normal)
cityButton.setImage(UIImage(named:"home_down"), for: .normal)
cityButton.addTarget(self, action: #selector(onClickPushCityView), for:UIControlEvents.touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: cityButton)
}
// received the notification
func onCityChange(notification: NSNotification) {
if let currentCity = notification.object as! String? {
cityButton.setTitle(currentCity, for: .normal)
}
}
// received the button click event
func onClickPushCityView() {
let cityViewVC = CityViewController()
cityViewVC.cityName = self.cityButton.title(for: .normal)
let nav = MainNavigationController(rootViewController: cityViewVC)
present(nav, animated: true, completion: nil)
}
func showMapViewUI() {
mapButton = TextImageButton(frame: CGRect.CGRectMake(40, 300, 80, 44))
mapButton.setTitle("Map", for: .normal)
mapButton.titleLabel?.font = theme.appNaviItemFont
mapButton.setTitleColor(UIColor.black, for: UIControlState.normal)
mapButton.setImage(UIImage(named:"home_down"), for: .normal)
mapButton.addTarget(self, action: #selector(onClickPushMapView),
for:UIControlEvents.touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: mapButton)
}
func onClickPushMapView() {
let mapViewVC = MapViewController()
let nav = MainNavigationController(rootViewController: mapViewVC)
present(nav, animated: true, completion: nil)
}
func toAboutViewController() {
//let storyboard = UIStoryboard(name:kUIStoryboardName_Setting, bundle: nil)
//let aboutVC = storyboard.instantiateViewController(withIdentifier:kUIViewControllerId_AboutVC) as! AboutViewController
let aboutVC = AboutViewController()
let nav = MainNavigationController(rootViewController: aboutVC)
self.present(nav, animated: true, completion: nil)
}
func toPurchaseViewController() {
let purchaseVC = PurchaseViewController()
let nav = MainNavigationController(rootViewController: purchaseVC)
self.present(nav, animated: true, completion: nil)
}
}
//MARK: - ========== UITableViewDelegate, UITableViewDataSource ==========
extension SettingViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = SettingCell.settingCellWithTableView(tableView)
//cell.setimageView.image = UIImage(named:images[indexPath.row] as! String)
cell.titleLabel.text = titles[indexPath.row] as? String
if indexPath.row == SettingCellType.clean.hashValue {
cell.bottomView.isHidden = false //true
cell.sizeLabel.isHidden = false
cell.sizeLabel.text = String().appendingFormat("%.2f M", FileUtils.folderSize(path:appCachesPath!))
} else {
cell.bottomView.isHidden = false
cell.sizeLabel.isHidden = true
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case SettingCellType.about.hashValue:
self.toAboutViewController()
case SettingCellType.score.hashValue:
break
case SettingCellType.recommend.hashValue:
break
case SettingCellType.feedback.hashValue:
break
case SettingCellType.clean.hashValue:
weak var tmpSelf = self
FileUtils.cleanFolder(path:appCachesPath!, complete: {
() -> () in tmpSelf!.tableView.reloadData()
})
case SettingCellType.purchase.hashValue:
self.toPurchaseViewController()
case SettingCellType.verinfo.hashValue:
appShare.openURL(NSURL(string:theme.GitHubURL)! as URL)
default:
break
}
}
}
class TextImageButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel?.font = theme.appNaviItemFont
titleLabel?.contentMode = UIViewContentMode.center
imageView?.contentMode = UIViewContentMode.left
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implement")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel?.sizeToFit()
titleLabel?.frame = CGRect.CGRectMake(-5, 0, titleLabel!.width, height)
imageView?.frame = CGRect.CGRectMake(titleLabel!.width + 3 - 5, 0, width - titleLabel!.width - 3, height)
}
}
|
mit
|
efec489d3c5a01602f3b3bbd273a166f
| 37.528169 | 143 | 0.651435 | 4.897941 | false | false | false | false |
LonelyHusky/SCWeibo
|
SCWeibo/Classes/View/Home/SCHomeViewController.swift
|
1
|
2212
|
//
// SCHomeViewController.swift
// SCWeibo
//
// Created by 云卷云舒丶 on 16/7/19.
//
//
import UIKit
class SCHomeViewController: SCVisitorViewController {
//cell ID
let SCStatusID = "SCStatusCell"
var statusArray = [SCStatus]()
private lazy var statusListViewModel : SCStatusListViewModel = SCStatusListViewModel()
override func viewDidLoad() {
super.viewDidLoad()
// 是否登录
if !isLogin {
visitorView?.setupVisitorViewInfo(nil, title: nil)
return
}
setupUI()
// 网络请求
loadData()
}
private func setupUI(){
tableView.dataSource = self
tableView.registerClass(SCStatusCell.self, forCellReuseIdentifier: SCStatusID)
// 自动计算行高
tableView.rowHeight = UITableViewAutomaticDimension
// 设置预估行高。确认在所有的 cell 在没有加载完成之前的tableView的contentSize。让tableView滚动起来
tableView.estimatedRowHeight = 200
// 隐藏分割线
tableView.separatorStyle = .None
tableView.backgroundColor = UIColor(white: 242/255, alpha: 1)
}
private func loadData(){
statusListViewModel.loadData { (isSuccess) in
if isSuccess{
// 刷新tebVIew
self.tableView.reloadData()
}else{
print("数据请求失败")
}
}
}
}
extension SCHomeViewController:UITableViewDataSource{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statusListViewModel.statusArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(SCStatusID, forIndexPath: indexPath) as! SCStatusCell
// print( statusListViewModel.statusArray[indexPath.row])
// 给cell附值
cell.statusViewModel = statusListViewModel.statusArray[indexPath.row]
return cell
}
}
|
mit
|
c9d32e25265f2e2afb02afdba181b7b0
| 21.630435 | 116 | 0.612392 | 5.028986 | false | false | false | false |
neo1125/NumberPad
|
NumberPad/BasicNumberPadViewController.swift
|
1
|
2305
|
import UIKit
class BasicNumberPadViewController: UIViewController {
@IBOutlet var textfield: UITextField!
private lazy var numberPad: NumberPad = {
let pad = NumberPad()
pad.delegate = self
pad.clearKeyPosition = .left
pad.customKeyText = "입력"
pad.customKeyTitleColor = UIColor.white
pad.backgroundColor = .white
pad.keyBorderColor = UIColor.white
pad.keyBorderWidth = 1
pad.keyScale = 0.8
pad.style = .circle
if #available(iOS 11.0, *) {
pad.customKeyBackgroundColor = UIColor(named: "CustomKeyBackground")
pad.customKeyHighlightColor = UIColor(named: "CustomKeyHighlight")
pad.customKeyBorderColor = UIColor(named: "CustomKeyBackground")
pad.customKeyBorderWidth = 1
} else {
pad.customKeyBackgroundColor = UIColor(red: 0.203, green: 0.594, blue: 0.859, alpha: 1)
pad.customKeyHighlightColor = UIColor(red: 0.214, green: 0.651, blue: 0.941, alpha: 1)
pad.customKeyBorderColor = UIColor(red: 0.203, green: 0.594, blue: 0.859, alpha: 1)
pad.customKeyBorderWidth = 1
}
return pad
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(numberPad)
view.addConstraints(withFormat: "H:|[v0]|", views: numberPad)
view.addConstraints(withFormat: "V:|-200-[v0]|", views: numberPad)
}
}
extension BasicNumberPadViewController: NumberPadDelegate {
func keyPressed(key: NumberKey?) {
guard let number = key else {
return
}
switch number {
case .clear:
guard !(textfield.text?.isEmpty ?? true) else {
return
}
textfield.text?.removeLast()
case .custom:
let alert = UIAlertController(title: "Custom NumberPad Event",
message: "\(textfield.text ?? "") Send Number", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
default:
textfield.text?.append("\(number.rawValue)")
}
}
}
|
mit
|
12e673f71778189332af80680ec0c114
| 35.52381 | 113 | 0.586267 | 4.620482 | false | false | false | false |
vkozlovskyi/JellyView
|
JellyView-Example/JellyView/Path/RightSidePathBuilder.swift
|
1
|
4482
|
//
// Created by Vladimir Kozlovskyi on 7/26/18.
// Copyright (c) 2018 Vladimir Kozlovskyi. All rights reserved.
//
import UIKit
public struct RightSidePathBuilder: PathBuilder {
func buildCurrentPath(inputData: PathInputData) -> Path {
let height = inputData.frame.height
let width = inputData.frame.width
let outerDelta = inputData.outerPointRatio * height
let curvePointX = width + inputData.touchPoint.x
let extraSpace = inputData.frame.height / Constants.extraSpaceDivider
let fstStartPoint = CGPoint(x: width, y: -extraSpace)
let fstEndPoint = CGPoint(x: curvePointX, y: inputData.touchPoint.y)
let fstControlPoint1 = CGPoint(x: width, y: inputData.touchPoint.y * inputData.innerPointRatio)
let fstControlPoint2 = CGPoint(x: curvePointX, y: inputData.touchPoint.y - outerDelta)
let sndStartPoint = fstEndPoint
let sndEndPoint = CGPoint(x: width, y: height + extraSpace)
let sndControlPoint1 = CGPoint(x: curvePointX, y: inputData.touchPoint.y + outerDelta)
let sndControlPoint2 = CGPoint(x: width, y: inputData.touchPoint.y + (height - inputData.touchPoint.y) * (1.0 - inputData.innerPointRatio))
let fstCurve = Curve(startPoint: fstStartPoint,
endPoint: fstEndPoint,
controlPoint1: fstControlPoint1,
controlPoint2: fstControlPoint2)
let sndCurve = Curve(startPoint: sndStartPoint,
endPoint: sndEndPoint,
controlPoint1: sndControlPoint1,
controlPoint2: sndControlPoint2)
let path = Path(fstCurve: fstCurve, sndCurve: sndCurve)
return path
}
func buildInitialPath(inputData: PathInputData) -> Path {
let height = inputData.frame.height
let width = inputData.frame.width
let outerDelta = inputData.outerPointRatio * height
let extraSpace = inputData.frame.height / Constants.extraSpaceDivider
let centerY = height / 2
let fstStartPoint = CGPoint(x: width, y: -extraSpace)
let fstEndPoint = CGPoint(x: width, y: centerY)
let fstControlPoint1 = CGPoint(x: width, y: centerY * inputData.innerPointRatio)
let fstControlPoint2 = CGPoint(x: width, y: centerY - outerDelta)
let sndStartPoint = fstEndPoint
let sndEndPoint = CGPoint(x: width, y: height + extraSpace)
let sndControlPoint1 = CGPoint(x: width, y: centerY + outerDelta)
let sndControlPoint2 = CGPoint(x: width, y: centerY + (height - centerY) * (1.0 - inputData.innerPointRatio))
let fstCurve = Curve(startPoint: fstStartPoint,
endPoint: fstEndPoint,
controlPoint1: fstControlPoint1,
controlPoint2: fstControlPoint2)
let sndCurve = Curve(startPoint: sndStartPoint,
endPoint: sndEndPoint,
controlPoint1: sndControlPoint1,
controlPoint2: sndControlPoint2)
let path = Path(fstCurve: fstCurve, sndCurve: sndCurve)
return path
}
func buildExpandedPath(inputData: PathInputData) -> Path {
let extraSpace = inputData.frame.height / Constants.extraSpaceDivider
let height = inputData.frame.height
let width = inputData.frame.width
let widthFinalPoint = width - (width * 2)
let centerY = height / 2
let delta = (width * 2) / 2 + widthFinalPoint
let fstStartPoint: CGPoint = CGPoint(x: width, y: -extraSpace)
let fstEndPoint: CGPoint = CGPoint(x: widthFinalPoint, y: centerY)
let fstControlPoint1: CGPoint = CGPoint(x: delta / 2, y: -extraSpace)
let fstControlPoint2: CGPoint = CGPoint(x: widthFinalPoint, y: centerY / 2)
let sndStartPoint: CGPoint = fstEndPoint
let sndEndPoint: CGPoint = CGPoint(x: width, y: height + extraSpace)
let sndControlPoint1: CGPoint = CGPoint(x: widthFinalPoint, y: centerY + extraSpace)
let sndControlPoint2: CGPoint = CGPoint(x: delta / 2, y: height + extraSpace)
let fstCurve = Curve(startPoint: fstStartPoint,
endPoint: fstEndPoint,
controlPoint1: fstControlPoint1,
controlPoint2: fstControlPoint2)
let sndCurve = Curve(startPoint: sndStartPoint,
endPoint: sndEndPoint,
controlPoint1: sndControlPoint1,
controlPoint2: sndControlPoint2)
let path = Path(fstCurve: fstCurve, sndCurve: sndCurve)
return path
}
}
|
mit
|
d58ae0aff3e42e8c9891bccc1598c787
| 41.685714 | 143 | 0.665997 | 4.326255 | false | false | false | false |
webelectric/AspirinKit
|
AspirinKit/Sources/SpriteKit/SKColor+Extensions.swift
|
1
|
6457
|
//
// SKColor.swift
// AspirinKit
//
// Copyright © 2015 - 2017 The Web Electric Corp.
//
// 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 SpriteKit
import CoreGraphics
//TODO add back hex string cache
//private var hexStringColorCache: NSCache<String, SKColor> = NSCache<String, SKColor>()
public extension SKColor {
// class func clearCaches() {
// hexStringColorCache.removeAll()
// }
public static var nxLabelColor:SKColor {
return SKColor.darkGray
}
public static var nxSecondaryLabelColor:SKColor {
return SKColor.darkGray
}
public var rgba:(r:Float, g:Float, b:Float, a:Float) {
var red:CGFloat = 0
var green:CGFloat = 0
var blue:CGFloat = 0
var alpha:CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (r: Float(red), g: Float(green), b: Float(blue), a: Float(alpha))
}
#if !os(macOS)
//TODO FIXME -- verify what is the best equivalent function to match NSColor's calibrated...
public convenience init(calibratedRed redc:CGFloat, green greenc:CGFloat, blue bluec:CGFloat, alpha alphac:CGFloat) {
self.init(red: redc, green: greenc, blue: bluec, alpha: alphac)
}
#endif
// A hex must be either 6 ("RRGGBB"), 7 ("#RRGGBB") or 8/9 characters ("#RRGGBBAA")
public convenience init(hexString: String) {
var hex = hexString.uppercased()
let hexLength = hex.characters.count
//remove # if present
if hex.hasPrefix("#") {
hex.removed(prefix: "#")
}
if hexLength == 3 || hexLength == 4 {
//format is 'rgb' or 'rgba', duplicate chars to convert to valid
hex = hex.characters.map( { "\($0)\($0)" } ).joined()
}
else if !(hexLength == 6 || hexLength == 8) {
// A hex must be either 6 (#RRGGBB), 8 characters (#RRGGBBAA)
print("improper call to create color from hex string, string length 6 ('RRGGBB'), 7 ('#RRGGBB') or 8/9 characters ('#RRGGBBAA')\n")
self.init(white: 0, alpha: 1)
return
}
// var resultColor: SKColor? = hexStringColorCache.object(forKey: rgbHexString)
var alpha:Float = 100
var rgbOnlyHex = hex
if hexLength == 8 {
let strPos1 = hex.index(hex.endIndex, offsetBy: -2)
let strPos2 = hex.index(hex.startIndex, offsetBy: 5)
alpha = String(hex[strPos1...]).float ?? 1
rgbOnlyHex = String(hex[..<strPos2])
}
var rgb:UInt32 = 0
let s:Scanner = Scanner(string: rgbOnlyHex)
s.scanHexInt32(&rgb)
let redValue = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
let greenValue = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
let blueValue = CGFloat(rgb & 0x0000FF) / 255.0
let alphaValue = CGFloat(alpha / 100)
self.init(
red: redValue,
green: greenValue,
blue: blueValue,
alpha: alphaValue
)
}
public var hexString: String? {
let rgba = self.rgba
let hexString = String(format: "%02X%02X%02X%02X", Int(rgba.r * 255.0), Int(rgba.g * 255.0), Int(rgba.b * 255.0), Int(rgba.a * 255.0))
return hexString
}
public var inverse:SKColor? {
let cgColor = self.cgColor
let numberOfComponents = cgColor.numberOfComponents
// can't invert - the only component is the alpha value
if numberOfComponents == 1 {
return self
}
let oldComponents = cgColor.components
var newComponents:[CGFloat] = [CGFloat]()
for i in 0...(numberOfComponents-2) {
let oldValue:CGFloat = oldComponents![i]
newComponents.append(1 - oldValue)
}
//alpha value shouldn't be inverted
newComponents.append((oldComponents?[numberOfComponents-1])!)
if let newCGColor = CGColor(colorSpace: cgColor.colorSpace!, components: &newComponents) {
return SKColor(cgColor: newCGColor)
}
return nil
}
//see https://www.w3.org/WAI/ER/WD-AERT/#color-contrast
///range returned is 0-1 Float. Values of > 0.875 are probably not readable in a white background
///while a value of < 0.125 is probably not readable in a black background
public var brightness: CGFloat {
let rgba = self.rgba
let rVal = CGFloat(rgba.r * 255 * 299)
let gVal = CGFloat(rgba.g * 255 * 587)
let bVal = CGFloat(rgba.b * 255 * 114)
return (rVal + gVal + bVal) / CGFloat(255000);
}
public var isBright:Bool {
return self.brightness >= 0.5
}
public var isDark:Bool {
return !self.isBright
}
public func lighter() -> SKColor {
let colorChangeDif:CGFloat = 0.1
let components = self.cgColor.components
if components != nil {
return SKColor(red: min(components![0] + colorChangeDif, 1.0), green: min(components![1] + colorChangeDif, 1.0), blue: min(components![2] + colorChangeDif, 1.0), alpha: components![3])
}
return self
}
}
|
mit
|
bc6e7bf5529e115be0707f06a7e0be54
| 34.472527 | 200 | 0.599752 | 4.181347 | false | false | false | false |
caloon/NominatimSwift
|
Example/Nominatim/ViewController.swift
|
1
|
1372
|
//
// ViewController.swift
// Nominatim
//
// Created by caloon on 12/21/2017.
// Copyright (c) 2017 caloon. All rights reserved.
//
import UIKit
import Nominatim
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Search for Addresses
Nominatim.getLocation(fromAddress: "Stephansplatz, 1010 Vienna, Austria", completion: {(location) -> Void in
if location != nil {
print("Geolocation of Stephansplatz, 1010 Vienna, Austria: " + "lat=" + location!.latitude + " long=" + location!.longitude)
}
})
// Search for Landmarks
Nominatim.getLocation(fromAddress: "Schloss Neuschwanstein", completion: {(location) -> Void in
if location != nil {
print("Geolocation of Schloss Neuschwanstein: " + "lat=" + location!.latitude + " long=" + location!.longitude)
}
})
// Search with Latitude and Longitude
Nominatim.getLocation(fromLatitude: "55.6867243", longitude: "12.5700724", completion: {(error, location) -> Void in
if location != nil {
print("City for geolocation 55.6867243/12.5700724: " + location!.city!)
}
})
}
}
|
mit
|
b085598f58d31740b77d2f144f7bf029
| 29.488889 | 142 | 0.556851 | 4.26087 | false | false | false | false |
MoZhouqi/KMPlaceholderTextView
|
Example/ViewController.swift
|
1
|
1982
|
//
// ViewController.swift
// KMPlaceholderTextView
//
// Created by Zhouqi Mo on 3/4/15.
// Copyright (c) 2015 Zhouqi Mo. All rights reserved.
//
import UIKit
import KMPlaceholderTextView
class ViewController: UIViewController {
@IBOutlet weak var placeholderTextView: KMPlaceholderTextView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWasShown(notification: NSNotification)
{
let info = notification.userInfo!
var kbRect = (info[UIResponder.keyboardFrameEndUserInfoKey]! as! NSValue).cgRectValue
kbRect = view.convert(kbRect, from: nil)
var contentInsets = placeholderTextView.contentInset
contentInsets.bottom = kbRect.size.height
placeholderTextView.contentInset = contentInsets
placeholderTextView.scrollIndicatorInsets = contentInsets
}
@objc func keyboardWillBeHidden(notification: NSNotification)
{
var contentInsets = placeholderTextView.contentInset
contentInsets.bottom = 0.0
placeholderTextView.contentInset = contentInsets
placeholderTextView.scrollIndicatorInsets = contentInsets
}
}
|
mit
|
5a83a41564a80f93eeecb70e09f64114
| 36.396226 | 171 | 0.729062 | 5.59887 | false | false | false | false |
ahoppen/swift
|
test/expr/closure/closures.swift
|
1
|
36185
|
// RUN: %target-typecheck-verify-swift
var func6 : (_ fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{53-53= _ in}}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0
// expected-error@-1 {{cannot convert value of type 'Double' to closure result type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{27-27=()}} // expected-note {{Remove '=' to make 'closure7' a computed property}}{{20-22=}}
var capturedVariable = 1
var closure8 = { [capturedVariable] in
capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}}
}
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(_ a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6({$0 + $1}) // Closure with two named anonymous arguments
func6({($0) + $1}) // Closure with sequence expr inferred type
func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}}
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
// expected-error@-1 {{cannot convert value of type '(Int) -> Int' to expected argument type '()'}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11) // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}}
funcdecl1(123, 444)
// Calls.
4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6({ a, b -> Int in a+b})
// Return type inference.
func6({ a,b in a+b })
// Infer incompatible type.
func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments.
func6({ _,_ in 4 })
func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, Int) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(_ x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(_ p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(_ a: Any) -> Int { return 1 }
assert(f0(1) == 1)
// TODO(diagnostics): Bad diagnostic - should be `circular reference`
var selfRef = { selfRef() }
// expected-error@-1 {{unable to infer closure type in the current context}}
// TODO: should be an error `circular reference` but it's diagnosed via overlapped requests
var nestedSelfRef = {
var recursive = { nestedSelfRef() }
// expected-warning@-1 {{variable 'recursive' was never mutated; consider changing to 'let' constant}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
func f(_: String) {}
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}}
var a4 = { (z: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}}
}
var a5 = { (_: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}}
}
}
func doStuff(_ fn : @escaping () -> Int) {}
func doVoidStuff(_ fn : @escaping () -> ()) {}
func doVoidStuffNonEscaping(_ fn: () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base or an explicit capture.
doVoidStuff({ self.x += 1 })
doVoidStuff({ [self] in x += 1 })
doVoidStuff({ [self = self] in x += 1 })
doVoidStuff({ [unowned self] in x += 1 })
doVoidStuff({ [unowned(unsafe) self] in x += 1 })
doVoidStuff({ [unowned self = self] in x += 1 })
doStuff({ [self] in x+1 })
doStuff({ [self = self] in x+1 })
doStuff({ self.x+1 })
doStuff({ [unowned self] in x+1 })
doStuff({ [unowned(unsafe) self] in x+1 })
doStuff({ [unowned self = self] in x+1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff({ doStuff({ x+1 })}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{28-28= [self] in}} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{19-19=self.}}
doVoidStuff({ _ = "\(x)"}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff({ [y = self] in x += 1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{33-33=self.}}
doStuff({ [y = self] in x+1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in x += 1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in x+1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in x += 1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in x+1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
// Methods follow the same rules as properties, uses of 'self' without capturing must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff { () -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{35-35=self.}}
doVoidStuff { [y = self] in _ = method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{37-37=self.}}
doStuff({ [y = self] in method() }) // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in _ = method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in _ = method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff { _ = self.method() }
doVoidStuff { [self] in _ = method() }
doVoidStuff { [self = self] in _ = method() }
doVoidStuff({ [unowned self] in _ = method() })
doVoidStuff({ [unowned(unsafe) self] in _ = method() })
doVoidStuff({ [unowned self = self] in _ = method() })
doStuff { self.method() }
doStuff { [self] in method() }
doStuff({ [self = self] in method() })
doStuff({ [unowned self] in method() })
doStuff({ [unowned(unsafe) self] in method() })
doStuff({ [unowned self = self] in method() })
// When there's no space between the opening brace and the first expression, insert it
doStuff {method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in }} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
doVoidStuff {_ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doVoidStuff {() -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{34-34=self.}}
// With an empty capture list, insertion should be suggested without a comma
doStuff { [] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{21-21=self.}}
doStuff { [ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doStuff { [ /* This space intentionally left blank. */ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{65-65=self.}}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}}
doStuff { [ // Nothing in this capture list!
]
in
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{9-9=self.}}
}
// An inserted capture list should be on the same line as the opening brace, immediately following it.
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+2 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
// Note: Trailing whitespace on the following line is intentional and should not be removed!
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff { // We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {// We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// String interpolation should offer the diagnosis and fix-its at the expected locations
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
doVoidStuff { _ = "\(x+1)" } // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
// If we already have a capture list, self should be added to the list
let y = 1
doStuff { [y] in method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doStuff { [ // expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
y // expected-warning {{capture 'y' was never used}}
] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{23-23= [self] in }} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
// If the implicit self is of value type, no diagnostic should be produced.
struct ImplicitSelfAllowedInStruct {
var x = 42
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ x += 1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
enum ImplicitSelfAllowedInEnum {
case foo
var x: Int { 42 }
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
class SomeClass {
var field : SomeClass?
var `class` : SomeClass?
var `in`: Int = 0
func foo() -> Int {}
}
func testCaptureBehavior(_ ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{invalid redeclaration of 'v1'}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
doStuff { [weak self.field] in field!.foo() }
// expected-error@-1{{fields may only be captured by assigning to a specific name}}{{21-21=field = }}
// expected-error@-2{{reference to property 'field' in closure requires explicit use of 'self' to make capture semantics explicit}}
// expected-note@-3{{reference 'self.' explicitly}} {{36-36=self.}}
// expected-note@-4{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
doStuff { [self.field] in field!.foo() }
// expected-error@-1{{fields may only be captured by assigning to a specific name}}{{16-16=field = }}
// expected-error@-2{{reference to property 'field' in closure requires explicit use of 'self' to make capture semantics explicit}}
// expected-note@-3{{reference 'self.' explicitly}} {{31-31=self.}}
// expected-note@-4{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
doStuff { [self.field!.foo()] in 32 }
//expected-error@-1{{fields may only be captured by assigning to a specific name}}
doStuff { [self.class] in self.class!.foo() }
//expected-error@-1{{fields may only be captured by assigning to a specific name}}{{16-16=`class` = }}
doStuff { [self.`in`] in `in` }
//expected-note@-1{{capture 'self' explicitly to enable implicit 'self' in this closure}}
//expected-error@-2{{fields may only be captured by assigning to a specific name}}{{16-16=`in` = }}
//expected-error@-3{{reference to property 'in' in closure requires explicit use of 'self' to make capture semantics explicit}}
//expected-note@-4{{reference 'self.' explicitly}}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 { // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{top-level statement cannot begin with a closure expression}}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> (Int) -> Int {
return { x in
class A {
let d : Int = 0
}
return 0
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(_ f: () -> ()) {}
var i: Int = 1
// expected-warning @+1 {{expression of type 'Int' is unused}}
takesVoidFunc({i})
// expected-warning @+1 {{expression of type 'Int' is unused}}
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = {
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(_ fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(_ a: () -> T) {}
func genericTwo<T>(_ a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{cannot find type 'Undeclared' in scope}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0 // expected-warning {{variable 'width' was never mutated}}
var height = 0 // expected-warning {{variable 'height' was never mutated}}
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{cannot find type 'asdf' in scope}} expected-warning {{variable 'bufs' was never used}}
[UInt8](repeating: 0, count: width*height)
}
}
// <rdar://problem/25993258>
// Don't crash if we infer a closure argument to have a tuple type containing inouts.
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258a() {
r25993258_helper { x in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
func r25993258b() {
r25993258_helper { _ in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// We have to map the captured var type into the right generic environment.
class GenericClass<T> {}
func lvalueCapture<T>(c: GenericClass<T>) {
var cc = c
weak var wc = c
func innerGeneric<U>(_: U) {
_ = cc
_ = wc
cc = wc!
}
}
// Don't expose @lvalue-ness in diagnostics.
let closure = {
var helper = true // expected-warning {{variable 'helper' was never mutated; consider changing to 'let' constant}}
return helper
}
// SR-9839
func SR9839(_ x: @escaping @convention(block) () -> Void) {}
func id<T>(_ x: T) -> T {
return x
}
var qux: () -> Void = {}
SR9839(qux)
SR9839(id(qux)) // expected-error {{conflicting arguments to generic parameter 'T' ('() -> Void' vs. '@convention(block) () -> Void')}}
func forceUnwrap<T>(_ x: T?) -> T {
return x!
}
var qux1: (() -> Void)? = {}
SR9839(qux1!)
SR9839(forceUnwrap(qux1))
// rdar://problem/65155671 - crash referencing parameter of outer closure
func rdar65155671(x: Int) {
{ a in
_ = { [a] in a }
}(x)
}
func sr3186<T, U>(_ f: (@escaping (@escaping (T) -> U) -> ((T) -> U))) -> ((T) -> U) {
return { x in return f(sr3186(f))(x) }
}
class SR3186 {
init() {
// expected-warning@+1{{capture 'self' was never used}}
let v = sr3186 { f in { [unowned self, f] x in x != 1000 ? f(x + 1) : "success" } }(0)
print("\(v)")
}
}
// Apply the explicit 'self' rule even if it refers to a capture, if
// we're inside a nested closure
class SR14120 {
func operation() {}
func test1() {
doVoidStuff { [self] in
operation()
}
}
func test2() {
doVoidStuff { [self] in
doVoidStuff {
// expected-warning@+3 {{call to method 'operation' in closure requires explicit use of 'self'}}
// expected-note@-2 {{capture 'self' explicitly to enable implicit 'self' in this closure}}
// expected-note@+1 {{reference 'self.' explicitly}}
operation()
}
}
}
func test3() {
doVoidStuff { [self] in
doVoidStuff { [self] in
operation()
}
}
}
func test4() {
doVoidStuff { [self] in
doVoidStuff {
self.operation()
}
}
}
func test5() {
doVoidStuff { [self] in
doVoidStuffNonEscaping {
operation()
}
}
}
func test6() {
doVoidStuff { [self] in
doVoidStuff { [self] in
doVoidStuff {
// expected-warning@+3 {{call to method 'operation' in closure requires explicit use of 'self'}}
// expected-note@-2 {{capture 'self' explicitly to enable implicit 'self' in this closure}}
// expected-note@+1 {{reference 'self.' explicitly}}
operation()
}
}
}
}
}
// SR-14678
func call<T>(_ : Int, _ f: () -> (T, Int)) -> (T, Int) {
f()
}
func testSR14678() -> (Int, Int) {
call(1) { // expected-error {{cannot convert return expression of type '((), Int)' to return type '(Int, Int)'}}
(print("hello"), 0)
}
}
func testSR14678_Optional() -> (Int, Int)? {
call(1) { // expected-error {{cannot convert return expression of type '((), Int)' to return type '(Int, Int)'}}
(print("hello"), 0)
}
}
// SR-13239
func callit<T>(_ f: () -> T) -> T {
f()
}
func callitArgs<T>(_ : Int, _ f: () -> T) -> T {
f()
}
func callitArgsFn<T>(_ : Int, _ f: () -> () -> T) -> T {
f()()
}
func callitGenericArg<T>(_ a: T, _ f: () -> T) -> T {
f()
}
func callitTuple<T>(_ : Int, _ f: () -> (T, Int)) -> T {
f().0
}
func callitVariadic<T>(_ fs: () -> T...) -> T {
fs.first!()
}
func testSR13239_Tuple() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitTuple(1) { // expected-note@:18{{generic parameter 'T' inferred as '()' from closure return expression}}
(print("hello"), 0)
}
}
func testSR13239() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callit { // expected-note@:10{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
}
}
func testSR13239_Args() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitArgs(1) { // expected-note@:17{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
}
}
func testSR13239_ArgsFn() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitArgsFn(1) { // expected-note@:19{{generic parameter 'T' inferred as '()' from closure return expression}}
{ print("hello") }
}
}
func testSR13239MultiExpr() -> Int {
callit {
print("hello")
return print("hello") // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
func testSR13239_GenericArg() -> Int {
// Generic argument is inferred as Int from first argument literal, so no conflict in this case.
callitGenericArg(1) {
print("hello") // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
}
}
func testSR13239_Variadic() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitVariadic({ // expected-note@:18{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
})
}
func testSR13239_Variadic_Twos() -> Int {
// expected-error@+1{{cannot convert return expression of type '()' to return type 'Int'}}
callitVariadic({
print("hello")
}, {
print("hello")
})
}
// rdar://82545600: this should just be a warning until Swift 6
public class TestImplicitCaptureOfExplicitCaptureOfSelfInEscapingClosure {
var property = false
private init() {
doVoidStuff { [unowned self] in
doVoidStuff {}
doVoidStuff { // expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}}
doVoidStuff {}
property = false // expected-warning {{reference to property 'property' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note {{reference 'self.' explicitly}}
}
}
}
}
|
apache-2.0
|
bf198514ccd98bce12868a9ff673ad91
| 48.298365 | 382 | 0.651071 | 3.71433 | false | false | false | false |
gregorysholl/mocha-utilities
|
MochaUtilities/Classes/Layout/Utils/OrientationUtil.swift
|
1
|
680
|
//
// OrientationUtils.swift
// Pods
//
// Created by Gregory Sholl e Santos on 05/06/17.
//
//
import UIKit
// MARK: - Get-Only Properties
public class OrientationUtil {
// MARK: Get
public static var orientation: UIInterfaceOrientation {
return UIApplication.shared.statusBarOrientation
}
// MARK: Validation
public static var portrait: Bool {
return orientation == .portrait
}
public static var upsideDown: Bool {
return orientation == .portraitUpsideDown
}
public static var landscape: Bool {
return orientation == .landscapeLeft || orientation == .landscapeRight
}
}
|
mit
|
587d823ebbd41101e8dd2ab2faf87671
| 19 | 78 | 0.635294 | 4.822695 | false | false | false | false |
ahoppen/swift
|
test/SourceKit/CodeComplete/complete_stems.swift
|
21
|
5498
|
func aaaBbb() {}
func aaaaBbb() {}
func aaaCcc() {}
func aaaCccDdd() {}
func abc(def def: Int) {}
func abc(ghi ghi: Int) {}
func abc(ghi ghi: Int, jkl: Int) {}
func DEF() {}
func DEFG() {}
func HIJ() {}
func HIJ_KLM() {}
func HIJ_KLM_NOP() {}
func HIJ_KLM_QRS() {}
func HIJ_KLM(NOP NOP: Int) {}
func HIJ_KLM(NOP_QRS NOP_QRS: Int) {}
func HIJZ() {}
func test001() {
#^GLOBAL_FUNC_0,a,aaaC,abc,def,hij^#
}
// RUN: %complete-test %s -no-fuzz -group=stems -tok=GLOBAL_FUNC_0 | %FileCheck %s -check-prefix=GLOBAL_FUNC_0
// GLOBAL_FUNC_0-LABEL: Results for filterText: a [
// GLOBAL_FUNC_0-NEXT: aaa:
// GLOBAL_FUNC_0-NEXT: aaaBbb()
// GLOBAL_FUNC_0-NEXT: aaaCcc:
// GLOBAL_FUNC_0-NEXT: aaaCcc()
// GLOBAL_FUNC_0-NEXT: aaaCccDdd()
// GLOBAL_FUNC_0-NEXT: aaaaBbb()
// GLOBAL_FUNC_0-NEXT: abc(:
// GLOBAL_FUNC_0-NEXT: abc(def: Int)
// GLOBAL_FUNC_0-NEXT: abc(ghi:
// GLOBAL_FUNC_0-NEXT: abc(ghi: Int)
// GLOBAL_FUNC_0-NEXT: abc(ghi: Int, jkl: Int)
// GLOBAL_FUNC_0: ]
// GLOBAL_FUNC_0-LABEL: Results for filterText: aaaC [
// GLOBAL_FUNC_0-NEXT: aaaCcc()
// GLOBAL_FUNC_0-NEXT: aaaCccDdd()
// GLOBAL_FUNC_0-NEXT: ]
// GLOBAL_FUNC_0-LABEL: Results for filterText: abc [
// GLOBAL_FUNC_0-NEXT: abc(def: Int)
// FIXME: rdar://22062152 Missing sub-groups when there is a common stem to all
// results.
// DISABLED: abc(ghi:
// GLOBAL_FUNC_0-NEXT: abc(ghi: Int)
// GLOBAL_FUNC_0-NEXT: abc(ghi: Int, jkl: Int)
// GLOBAL_FUNC_0-NEXT: ]
// GLOBAL_FUNC_0-LABEL: Results for filterText: def [
// GLOBAL_FUNC_0-NEXT: DEF()
// GLOBAL_FUNC_0-NEXT: DEFG()
// GLOBAL_FUNC_0: ]
// GLOBAL_FUNC_0-LABEL: Results for filterText: hij [
// FIXME: rdar://22062152 Missing sub-groups when there is a common stem to all
// results. Should be -NEXT, and should remove HIJZ() above.
// GLOBAL_FUNC_0: HIJ()
// GLOBAL_FUNC_0-NEXT: HIJ_KLM:
// GLOBAL_FUNC_0-NEXT: HIJ_KLM(:
// GLOBAL_FUNC_0-NEXT: HIJ_KLM()
// GLOBAL_FUNC_0-NEXT: HIJ_KLM(NOP:
// GLOBAL_FUNC_0-NEXT: HIJ_KLM(NOP: Int)
// GLOBAL_FUNC_0-NEXT: HIJ_KLM(NOP_QRS: Int)
// GLOBAL_FUNC_0-NEXT: HIJ_KLM_:
// GLOBAL_FUNC_0-NEXT: HIJ_KLM_NOP()
// GLOBAL_FUNC_0-NEXT: HIJ_KLM_QRS()
// GLOBAL_FUNC_0: ]
struct S {
func aaaBbb() {}
func aaaaBbb() {}
func aaaCcc() {}
func aaaCccDdd() {}
func abc(def def: Int) {}
func abc(ghi ghi: Int) {}
func abc(ghi ghi: Int, jkl: Int) {}
func DEF() {}
func DEFG() {}
func HIJ() {}
func HIJ_KLM() {}
func HIJ_KLM_NOP() {}
func HIJ_KLM_QRS() {}
func HIJ_KLM(NOP NOP: Int) {}
func HIJ_KLM(NOP_QRS NOP_QRS: Int) {}
}
func test002(x: S) {
x.#^S_QUALIFIED_0^#
}
// RUN: %complete-test %s -no-fuzz -group=stems -tok=S_QUALIFIED_0 | %FileCheck %s -check-prefix=S_QUALIFIED_0
// S_QUALIFIED_0: aaa:
// S_QUALIFIED_0-NEXT: aaaBbb()
// S_QUALIFIED_0-NEXT: aaaCcc:
// S_QUALIFIED_0-NEXT: aaaCcc()
// S_QUALIFIED_0-NEXT: aaaCccDdd()
// S_QUALIFIED_0-NEXT: aaaaBbb()
// S_QUALIFIED_0-NEXT: abc(:
// S_QUALIFIED_0-NEXT: abc(def: Int)
// S_QUALIFIED_0-NEXT: abc(ghi::
// S_QUALIFIED_0-NEXT: abc(ghi: Int)
// S_QUALIFIED_0-NEXT: abc(ghi: Int, jkl: Int)
// S_QUALIFIED_0-NEXT: DEF()
// S_QUALIFIED_0-NEXT: DEFG()
// S_QUALIFIED_0-NEXT: HIJ:
// S_QUALIFIED_0-NEXT: HIJ()
// S_QUALIFIED_0-NEXT: HIJ_KLM:
// S_QUALIFIED_0-NEXT: HIJ_KLM(:
// S_QUALIFIED_0-NEXT: HIJ_KLM()
// S_QUALIFIED_0-NEXT: HIJ_KLM(NOP:
// S_QUALIFIED_0-NEXT: HIJ_KLM(NOP: Int)
// S_QUALIFIED_0-NEXT: HIJ_KLM(NOP_QRS: Int)
// S_QUALIFIED_0-NEXT: HIJ_KLM_:
// S_QUALIFIED_0-NEXT: HIJ_KLM_NOP()
// S_QUALIFIED_0-NEXT: HIJ_KLM_QRS()
struct T {
init() {}
init(abc: Int) {}
init(abcDef: Int) {}
init(abcDefGhi: Int) {}
func foo() {}
subscript(x x: Int) -> Int {}
subscript(x_y x: Int) -> Int {}
subscript(x_y_z x: Int) -> Int {}
}
// RUN: %complete-test %s -no-fuzz -add-inner-results -no-inner-operators -group=stems -tok=T_POSTFIX_0 | %FileCheck %s -check-prefix=T_POSTFIX_0
func test003() {
T#^T_POSTFIX_0^#
}
// T_POSTFIX_0: (:
// T_POSTFIX_0-NEXT: ()
// T_POSTFIX_0-NEXT: (abc:
// T_POSTFIX_0-NEXT: (abc: Int)
// T_POSTFIX_0-NEXT: (abcDef:
// T_POSTFIX_0-NEXT: (abcDef: Int)
// T_POSTFIX_0-NEXT: (abcDefGhi: Int)
// T_POSTFIX_0-NEXT: foo(self: T)
// RUN: %complete-test %s -no-fuzz -add-inner-results -no-inner-operators -group=stems -tok=T_POSTFIX_1 | %FileCheck %s -check-prefix=T_POSTFIX_1
func test004(x: T) {
x#^T_POSTFIX_1^#
}
// T_POSTFIX_1: [x:
// T_POSTFIX_1-NEXT: [x: Int]
// T_POSTFIX_1-NEXT: [x_y:
// T_POSTFIX_1-NEXT: [x_y: Int]
// T_POSTFIX_1-NEXT: [x_y_z: Int]
// T_POSTFIX_1-NEXT:foo()
struct MyAnyA {}
struct MyAnyB {}
func myanyFunc() {}
struct MyAnyGenerator {}
struct MyAnyGenerationalGarbageCollector {}
// There is only one Any group rdar://problem/21550130
// RUN: %complete-test %s -no-fuzz -group=stems -tok=GLOBAL_FUNC_1 | %FileCheck %s -check-prefix=GLOBAL_FUNC_1
func test005() {
#^GLOBAL_FUNC_1,my^#
}
// GLOBAL_FUNC_1: Results for filterText: my [
// GLOBAL_FUNC_1-NEXT: MyAny:
// GLOBAL_FUNC_1-NEXT: MyAnyA
// GLOBAL_FUNC_1-NEXT: MyAnyB
// GLOBAL_FUNC_1-NEXT: MyAnyGenerationalGarbageCollector
// GLOBAL_FUNC_1-NEXT: MyAnyGenerator
// GLOBAL_FUNC_1-NEXT: myanyFunc()
// GLOBAL_FUNC_1-NEXT: ]
|
apache-2.0
|
89c9e30341d4004feca9e79b7a7c01cc
| 31.152047 | 145 | 0.597308 | 2.518552 | false | true | false | false |
naru-jpn/pencil
|
Sources/ReadWriteSet.swift
|
1
|
6182
|
//
// ReadWriteSet.swift
// Pencil
//
// Created by Naruki Chigira on 2017/02/07.
// Copyright © 2017年 naru. All rights reserved.
//
import Foundation
extension Set where Element: ReadWriteElement {
public static func value(from url: URL, options: Data.ReadingOptions = []) -> Set<Element>? {
do {
let data: Data = try Data(contentsOf: url, options: options)
let value: Set<Element>? = self.value(from: data)
return value
} catch {
return nil
}
}
public static func value(from data: Data) -> Set<Element>? {
let value: Set<Element>? = Pencil.read(data)
return value
}
public static func devide(data: Data) -> [Data]? {
// check identifier of data
let length: Int = { (data: Data) -> Int in
return Int(UInt8(data: data))
}(data.subdata(from: 0, with: MemoryLayout<UInt8>.size))
let name: String = String(data: data.subdata(from: MemoryLayout<UInt8>.size, with: Int(length)), encoding: .utf8) ?? ""
guard name == self.sPencilName else {
debugPrint("pencil: Type of data is \(name) but applying type is \(self.sPencilName).")
return nil
}
// count of element
var index = MemoryLayout<UInt8>.size + length
let countOfElement: UInt16 = UInt16(data: data.subdata(from: index, with: MemoryLayout<UInt16>.size))
// lengths of elements
index = index + MemoryLayout<UInt16>.size
let lengths = data.subdata(from: index, with: MemoryLayout<UInt32>.size*Int(countOfElement)).splited(with: MemoryLayout<UInt32>.size, repeated: Int(countOfElement)).map {
Int(UInt32(data: $0))
}
// array of data
index = index + MemoryLayout<UInt32>.size*Int(countOfElement)
let values: [Data] = data.subdata(from: index, with: data.count - index).splited(to: lengths)
return values
}
public static func read(_ values: [Data]) -> Set<Element>? {
let elements = values.flatMap { (data: Data) -> Element? in
let element: Element? = Pencil.read(data)
return element
}
return Set(elements)
}
}
extension Set where Element: CustomReadWriteElement {
public static func value(from url: URL, options: Data.ReadingOptions = []) -> Set<Element>? {
do {
let data: Data = try Data(contentsOf: url, options: options)
let value: Set<Element>? = self.value(from: data)
return value
} catch {
return nil
}
}
public static func value(from data: Data) -> Set<Element>? {
let value: Set<Element>? = Pencil.read(data)
return value
}
public static func devide(data: Data) -> [Data]? {
// check identifier of data
let length: Int = { (data: Data) -> Int in
return Int(UInt8(data: data))
}(data.subdata(from: 0, with: MemoryLayout<UInt8>.size))
let name: String = String(data: data.subdata(from: MemoryLayout<UInt8>.size, with: Int(length)), encoding: .utf8) ?? ""
guard name == self.sPencilName else {
debugPrint("pencil: Type of data is \(name) but applying type is \(self.sPencilName).")
return nil
}
// count of element
var index = MemoryLayout<UInt8>.size + length
let countOfElement: UInt16 = UInt16(data: data.subdata(from: index, with: MemoryLayout<UInt16>.size))
// lengths of elements
index = index + MemoryLayout<UInt16>.size
let lengths = data.subdata(from: index, with: MemoryLayout<UInt32>.size*Int(countOfElement)).splited(with: MemoryLayout<UInt32>.size, repeated: Int(countOfElement)).map {
Int(UInt32(data: $0))
}
// array of data
index = index + MemoryLayout<UInt32>.size*Int(countOfElement)
let values: [Data] = data.subdata(from: index, with: data.count - index).splited(to: lengths)
return values
}
public static func read(_ values: [Data]) -> Set<Element>? {
let elements = values.flatMap { (data: Data) -> Element? in
let element: Element? = Pencil.read(data)
return element
}
return Set(elements)
}
}
extension Set: Writable {
public static var sPencilName: String {
return "\(self)"
}
public var pencilName: String {
return "\(Mirror(reflecting: self).subjectType)"
}
public func writable() -> [Writable] {
return self.flatMap {
return $0 as? Writable
}
}
public var pencilDataLength: Int {
let writables: [Writable] = self.writable()
let elementsLength: Int = writables.reduce(0, {
$0 + MemoryLayout<UInt8>.size + $1.pencilName.lengthOfBytes(using: String.Encoding.utf8) + $1.pencilDataLength
})
return MemoryLayout<UInt16>.size + MemoryLayout<UInt32>.size*writables.count + elementsLength
}
public var pencilHead: [Data] {
let writables: [Writable] = self.writable()
let count: Data = {
var num: UInt16 = UInt16(writables.count)
return Data(buffer: UnsafeBufferPointer(start: &num, count: 1))
}()
let data: [Data] = writables.map { (writable: Writable) -> Int in
let identifierLength: Int = MemoryLayout<UInt8>.size + writable.pencilName.lengthOfBytes(using: String.Encoding.utf8)
return identifierLength + writable.pencilDataLength
}.map { (length: Int) -> Data in
var num: UInt32 = UInt32(length)
return Data(buffer: UnsafeBufferPointer(start: &num, count: 1))
}
return [count] + data
}
public var pencilBody: [Data] {
let writables: [Writable] = self.writable()
let data: [Data] = writables.map { element in
return (element.data as Data)
}
return data
}
}
|
mit
|
5b9e1222025208d6e69b0623910ed10a
| 34.511494 | 178 | 0.579867 | 4.209128 | false | false | false | false |
CalQL8ed-K-OS/CollectionType.compact
|
CollectionType.compact.playground/Pages/The Finale.xcplaygroundpage/Contents.swift
|
1
|
1909
|
let input:[Int?] = [nil, 1, 2, 6, 84, nil, 123, 24, 8]
let goal:[Int] = [1,2,6,84,123,24,8]
/*:
here is our pride and joy, it looks a lot like the free function on Array, but now it's a constrained protocol extension on CollectionType.
this gives all conformers to the CollectionType protocol that happen to hold an OptionalType this method, automagically.
*/
extension Collection where Iterator.Element : OptionalType {
var compact: [Iterator.Element.Wrapped] {
var result:[Iterator.Element.Wrapped] = []
for item in self where item.hasValue {
result.append(item.unwrap())
}
return result
}
}
/*:
but wait, ¿what the heck is the OptionalType protocol?
we define this protocol for a few basic things needed in the final compact method.
*/
protocol OptionalType {
associatedtype Wrapped
func unwrap() -> Wrapped
var hasValue: Bool { get }
}
/*:
then we make the existing Optional type conform to it.
arguably this protocol and extension belong in the standard library, but maybe there's a good reason it's not.
*/
extension Optional : OptionalType {
func unwrap() -> Wrapped {
return self!
}
var hasValue: Bool {
return self != nil
}
}
//: finally we see our method, happily trailing the value it's operating on, removing all `nil`s and changing the static type from an Optional to a non-Optional.
let output = input.compact
output == goal
/*:
notice that the autocompletion for the `goal` array, which is a non-Optional CollectionType, doesn't expose the compact method at all.
the value of this static type checking in limiting the number of options we programmers have to think about is the most powerful argument in its favor in my opinion.
comparing this to Ruby where any symbol is allowed anywhere because ¡interpretted languages, duh!, leaves me happy to be in a Swifter world.
*/
|
mit
|
13239515cdd4ff05eedd3f6c82fa3981
| 37.918367 | 167 | 0.71054 | 4.182018 | false | false | false | false |
rockbruno/swiftshield
|
Tests/SwiftShieldTests/FeatureTests.swift
|
1
|
14649
|
@testable import SwiftShieldCore
import XCTest
final class FeatureTests: XCTestCase {
func test_operators_areIgnored() throws {
let (obfs, store, delegate) = baseTestData()
let module = try testModule(withContents: """
struct Foo {
public static func +(lhs: Foo, rhs: Foo) -> Foo { return lhs }
}
struct Bar {}
func +(lhs: Bar, rhs: Bar) -> Bar { return lhs }
""")
store.obfuscationDictionary["Foo"] = "OBS1"
store.obfuscationDictionary["Bar"] = "OBS2"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
struct OBS1 {
public static func +(lhs: OBS1, rhs: OBS1) -> OBS1 { return lhs }
}
struct OBS2 {}
func +(lhs: OBS2, rhs: OBS2) -> OBS2 { return lhs }
""")
}
func test_CodingKeys_isIgnored() throws {
let (obfs, store, delegate) = baseTestData()
let module = try testModule(withContents: """
struct Foo: Codable {
enum FooCodingKeys: CodingKey {
case a
case b
case c
}
enum RandomEnum {
case d
case e
case f
}
}
""")
store.obfuscationDictionary["Foo"] = "OBS1"
store.obfuscationDictionary["a"] = "OBS2"
store.obfuscationDictionary["b"] = "OBS3"
store.obfuscationDictionary["c"] = "OBS4"
store.obfuscationDictionary["d"] = "OBS5"
store.obfuscationDictionary["e"] = "OBS6"
store.obfuscationDictionary["f"] = "OBS7"
store.obfuscationDictionary["RandomEnum"] = "OBS8"
store.obfuscationDictionary["FooCodingKeys"] = "OBS9"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
struct OBS1: Codable {
enum OBS9: CodingKey {
case a
case b
case c
}
enum OBS8 {
case OBS5
case OBS6
case OBS7
}
}
""")
}
func test_NamesToIgnore() throws {
let (obfs, store, delegate) = baseTestData(namesToIgnore: ["IgnoreClassName",
"CodingKeys"])
let module = try testModule(withContents: """
import Foundation
class IgnoreClassName: NSObject {}
struct Foo: Codable {
let a: String
enum CodingKeys: String, CodingKey {
case a
}
}
""")
store.obfuscationDictionary["IgnoreClassName"] = "OBS1"
store.obfuscationDictionary["Foo"] = "OBS2"
store.obfuscationDictionary["a"] = "OBS3"
store.obfuscationDictionary["CodingKeys"] = "OBS4"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
import Foundation
class IgnoreClassName: NSObject {}
struct OBS2: Codable {
let a: String
enum CodingKeys: String, CodingKey {
case a
}
}
""")
}
func test_internalFrameworkDelegateReferences_areIgnored() throws {
let (obfs, store, delegate) = baseTestData()
let module = try testModule(withContents: """
import UIKit
class SomeClass: NSObject {}
final class Foo: SomeClass, UITableViewDelegate {
func notADelegate() {}
var notADelegateProperty: Int { return 1 }
override var hash: Int { return 1 }
func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {}
}
""")
store.obfuscationDictionary["Foo"] = "OBS1"
store.obfuscationDictionary["notADelegate"] = "OBS2"
store.obfuscationDictionary["notADelegateProperty"] = "OBS3"
store.obfuscationDictionary["SomeClass"] = "OBS4"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
import UIKit
class OBS4: NSObject {}
final class OBS1: OBS4, UITableViewDelegate {
func OBS2() {}
var notADelegateProperty: Int { return 1 }
override var hash: Int { return 1 }
func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {}
}
""")
}
func test_ignorePublic_ignoresPublics() throws {
let (obfs, store, delegate) = baseTestData(ignorePublic: true)
let module = try testModule(withContents: """
import UIKit
open class Ignored {
public func ignored2() {}
open func ignored7() {}
public var ignored8 = 0
open var ignored12: Int { return 0 }
func notIgnored() {}
public static func ignored13() {}
}
struct NotIgnored2 {}
extension Int {
public func ignored3() {}
public var ignored9: Int {
return 0
}
func notIgnored3() {}
}
public var ignored11: String = ""
public func ignored4() {}
func notIgnored4() {}
public enum Bla {
case abc
}
//Broken.
//public extension Int {
// func ignored5() {}
// func ignored6() {}
//}
""")
store.obfuscationDictionary["notIgnored"] = "OBS1"
store.obfuscationDictionary["NotIgnored2"] = "OBS2"
store.obfuscationDictionary["notIgnored3"] = "OBS3"
store.obfuscationDictionary["notIgnored4"] = "OBS4"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
import UIKit
open class Ignored {
public func ignored2() {}
open func ignored7() {}
public var ignored8 = 0
open var ignored12: Int { return 0 }
func OBS1() {}
public static func ignored13() {}
}
struct OBS2 {}
extension Int {
public func ignored3() {}
public var ignored9: Int {
return 0
}
func OBS3() {}
}
public var ignored11: String = ""
public func ignored4() {}
func OBS4() {}
public enum Bla {
case abc
}
//Broken.
//public extension Int {
// func ignored5() {}
// func ignored6() {}
//}
""")
}
func test_files_withEmojis() throws {
let (obfs, store, delegate) = baseTestData()
let module = try testModule(withContents: """
enum JSON {
static func parse(_ a: String) -> String { return a }
}
extension String {
func unobfuscate() -> String { return self }
}
func l3️⃣og(_ a: String) -> String { return JSON.parse("") }
var paramsString = "foo"
struct Logger {
func log() {
log("Hello 👨👩👧👧 3 A̛͚̖ 3️⃣ response up message 📲: \\(JSON.parse(paramsString.unobfuscate()).description) 🇹🇩👫👨👩👧👧👨👨👦"); log("")
}
func log(_ a: String) {
_ = l3️⃣og("foo".unobfuscate())
}
}
""")
store.obfuscationDictionary["JSON"] = "OBS1"
store.obfuscationDictionary["parse"] = "OBS2"
store.obfuscationDictionary["unobfuscate"] = "OBS3"
store.obfuscationDictionary["log"] = "OBS4"
store.obfuscationDictionary["Logger"] = "OBS5"
store.obfuscationDictionary["l3️⃣og"] = "OBS6"
store.obfuscationDictionary["paramsString"] = "OBS7"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
enum OBS1 {
static func OBS2(_ a: String) -> String { return a }
}
extension String {
func OBS3() -> String { return self }
}
func OBS6(_ a: String) -> String { return OBS1.OBS2("") }
var OBS7 = "foo"
struct OBS5 {
func OBS4() {
OBS4("Hello 👨👩👧👧 3 A̛͚̖ 3️⃣ response up message 📲: \\(OBS1.OBS2(OBS7.OBS3()).description) 🇹🇩👫👨👩👧👧👨👨👦"); OBS4("")
}
func OBS4(_ a: String) {
_ = OBS6("foo".OBS3())
}
}
""")
}
func test_property_obfuscation() throws {
let (obfs, store, delegate) = baseTestData()
let module = try testModule(withContents: """
var prop1 = "a"
struct Foo {
static let prop2 = Foo()
let prop3 = 1
var prop4: String {
return ""
}
lazy var prop5 = {
return self.prop4
}()
}
extension Foo {
var prop6: String {
return ""
}
}
""")
store.obfuscationDictionary["Foo"] = "OBSFOO"
store.obfuscationDictionary["prop1"] = "OBS1"
store.obfuscationDictionary["prop2"] = "OBS2"
store.obfuscationDictionary["prop3"] = "OBS3"
store.obfuscationDictionary["prop4"] = "OBS4"
store.obfuscationDictionary["prop5"] = "OBS5"
store.obfuscationDictionary["prop6"] = "OBS6"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
var OBS1 = "a"
struct OBSFOO {
static let OBS2 = OBSFOO()
let OBS3 = 1
var OBS4: String {
return ""
}
lazy var OBS5 = {
return self.OBS4
}()
}
extension OBSFOO {
var OBS6: String {
return ""
}
}
""")
}
func test_property_obfuscation_ignoresCodableChildren() throws {
let (obfs, store, delegate) = baseTestData()
let module = try testModule(withContents: """
import Foundation
struct Foo {
let prop1: String
}
struct Bar: Codable {
let prop1: String
}
struct Bar2: Decodable {
let prop1: String
}
struct Bar3: Encodable {
let prop1: String
}
protocol WrapperProtocol: Decodable {}
protocol AnotherWrapper: WrapperProtocol {}
typealias SomeCodable = Codable
struct BarWithHiddenCodable: AnotherWrapper {
let prop1: String
}
struct BarWithTypealias: SomeCodable {
let prop1: String
}
struct BarExternal: CodableProtocolInAnotherFile {
let prop1: String
}
protocol SomeProt {}
class BarClass: Codable, SomeProt {
let prop1: String
}
""")
store.obfuscationDictionary["Foo"] = "OBSFOO"
store.obfuscationDictionary["Bar"] = "OBSBAR"
store.obfuscationDictionary["Bar2"] = "OBSBAR2"
store.obfuscationDictionary["Bar3"] = "OBSBAR3"
store.obfuscationDictionary["BarWithHiddenCodable"] = "OBSBARHIDDEN"
store.obfuscationDictionary["WrapperProtocol"] = "OBSWRAP"
store.obfuscationDictionary["AnotherWrapper"] = "OBSAN"
store.obfuscationDictionary["BarWithTypealias"] = "OBSAL"
store.obfuscationDictionary["BarExternal"] = "OBSEX"
store.obfuscationDictionary["BarClass"] = "OBSOBJC"
store.obfuscationDictionary["CodableProtocolInAnotherFile"] = "EXCOD"
store.obfuscationDictionary["SomeProt"] = "OBSSOMEPROT"
store.obfuscationDictionary["prop1"] = "OBS1"
store.obfuscationDictionary["prop2"] = "OBS2"
store.obfuscationDictionary["prop3"] = "OBS3"
store.obfuscationDictionary["prop4"] = "OBS4"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
import Foundation
struct OBSFOO {
let OBS1: String
}
struct OBSBAR: Codable {
let prop1: String
}
struct OBSBAR2: Decodable {
let prop1: String
}
struct OBSBAR3: Encodable {
let prop1: String
}
protocol OBSWRAP: Decodable {}
protocol OBSAN: OBSWRAP {}
typealias SomeCodable = Codable
struct OBSBARHIDDEN: OBSAN {
let prop1: String
}
struct OBSAL: SomeCodable {
let prop1: String
}
struct OBSEX: EXCOD {
let prop1: String
}
protocol OBSSOMEPROT {}
class OBSOBJC: Codable, OBSSOMEPROT {
let prop1: String
}
""")
}
func test_property_obfuscation_ignoresOBJCClasses() throws {
let (obfs, store, delegate) = baseTestData()
let module = try testModule(withContents: """
import Foundation
import UIKit
class BarClass: NSObject {
let prop1: String = ""
func method() {}
}
@objc class BarRaw: UIViewController {
let prop1: String = ""
func method() {}
}
""")
store.obfuscationDictionary["BarClass"] = "OBS1"
store.obfuscationDictionary["BarRaw"] = "OBS2"
store.obfuscationDictionary["method"] = "OBS3"
try obfs.registerModuleForObfuscation(module)
try obfs.obfuscate()
XCTAssertEqual(delegate.receivedContent[modifiableFilePath], """
import Foundation
import UIKit
class OBS1: NSObject {
let prop1: String = ""
func OBS3() {}
}
@objc class OBS2: UIViewController {
let prop1: String = ""
func OBS3() {}
}
""")
}
}
|
gpl-3.0
|
7aa50d83a4dfd9bc1d5604f6e5794927
| 28.118474 | 150 | 0.53017 | 4.415652 | false | true | false | false |
gmoral/SwiftTraining2016
|
Training_Swift/PeopleSkill.swift
|
1
|
1657
|
//
// PeopleSkill.swift
// Training_Swift
//
// Created by Guillermo Moral on 3/7/16.
// Copyright © 2016 Guillermo Moral. All rights reserved.
//
import UIKit
import SwiftyJSON
class PeopleSkill
{
var id: String?
var firstName : String?
var lastName : String?
var title: String?
var avatar: UIImage?
var avatarBase64EncodedString: String?
required init?(json: JSON)
{
id = json["_id"].string!
firstName = json["firstname"].string!
lastName = json["lastname"].string!
title = json["title"].string!
do
{
avatarBase64EncodedString = try parseAvatar(json)
} catch
{
avatarBase64EncodedString = ""
}
if !avatarBase64EncodedString!.isEmpty
{
let decodedData = NSData(base64EncodedString: avatarBase64EncodedString!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedimage = UIImage(data: decodedData!)
avatar = decodedimage! as UIImage
} else
{
avatar = UIImage(named: "Avatar.png")
}
}
lazy var fullName: String = {
guard let tmpFirstName = self.firstName,
let tmpLastName = self.lastName
where !tmpFirstName.isEmpty && !tmpLastName.isEmpty
else
{
return ""
}
return (tmpFirstName + " " + tmpLastName)
}()
func parseAvatar(json: JSON) throws -> String
{
guard let anAvatar = json["thumb"].string else { throw ParseError.Empty }
return anAvatar
}
}
|
mit
|
60c90b8ca1dd16dc3171e6b12ea20388
| 24.476923 | 136 | 0.567029 | 4.612813 | false | false | false | false |
nervousnet/nervousnet-HUB-iOS
|
Pods/Swifter/Sources/Socket.swift
|
5
|
5659
|
//
// Socket.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public enum SocketError: Error {
case socketCreationFailed(String)
case socketSettingReUseAddrFailed(String)
case bindFailed(String)
case listenFailed(String)
case writeFailed(String)
case getPeerNameFailed(String)
case convertingPeerNameFailed
case getNameInfoFailed(String)
case acceptFailed(String)
case recvFailed(String)
case getSockNameFailed(String)
}
open class Socket: Hashable, Equatable {
let socketFileDescriptor: Int32
private var shutdown = false
public init(socketFileDescriptor: Int32) {
self.socketFileDescriptor = socketFileDescriptor
}
deinit {
close()
}
public var hashValue: Int { return Int(self.socketFileDescriptor) }
public func close() {
if shutdown {
return
}
shutdown = true
Socket.close(self.socketFileDescriptor)
}
public func port() throws -> in_port_t {
var addr = sockaddr_in()
return try withUnsafePointer(to: &addr) { pointer in
var len = socklen_t(MemoryLayout<sockaddr_in>.size)
if getsockname(socketFileDescriptor, UnsafeMutablePointer(OpaquePointer(pointer)), &len) != 0 {
throw SocketError.getSockNameFailed(Errno.description())
}
#if os(Linux)
return ntohs(addr.sin_port)
#else
return Int(OSHostByteOrder()) != OSLittleEndian ? addr.sin_port.littleEndian : addr.sin_port.bigEndian
#endif
}
}
public func isIPv4() throws -> Bool {
var addr = sockaddr_in()
return try withUnsafePointer(to: &addr) { pointer in
var len = socklen_t(MemoryLayout<sockaddr_in>.size)
if getsockname(socketFileDescriptor, UnsafeMutablePointer(OpaquePointer(pointer)), &len) != 0 {
throw SocketError.getSockNameFailed(Errno.description())
}
return Int32(addr.sin_family) == AF_INET
}
}
public func writeUTF8(_ string: String) throws {
try writeUInt8(ArraySlice(string.utf8))
}
public func writeUInt8(_ data: [UInt8]) throws {
try writeUInt8(ArraySlice(data))
}
public func writeUInt8(_ data: ArraySlice<UInt8>) throws {
try data.withUnsafeBufferPointer {
try writeBuffer($0.baseAddress!, length: data.count)
}
}
public func writeData(_ data: NSData) throws {
try writeBuffer(data.bytes, length: data.length)
}
public func writeData(_ data: Data) throws {
try data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) -> Void in
try self.writeBuffer(pointer, length: data.count)
}
}
private func writeBuffer(_ pointer: UnsafeRawPointer, length: Int) throws {
var sent = 0
while sent < length {
#if os(Linux)
let s = send(self.socketFileDescriptor, pointer + sent, Int(length - sent), Int32(MSG_NOSIGNAL))
#else
let s = write(self.socketFileDescriptor, pointer + sent, Int(length - sent))
#endif
if s <= 0 {
throw SocketError.writeFailed(Errno.description())
}
sent += s
}
}
open func read() throws -> UInt8 {
var buffer = [UInt8](repeating: 0, count: 1)
let next = recv(self.socketFileDescriptor as Int32, &buffer, Int(buffer.count), 0)
if next <= 0 {
throw SocketError.recvFailed(Errno.description())
}
return buffer[0]
}
private static let CR = UInt8(13)
private static let NL = UInt8(10)
public func readLine() throws -> String {
var characters: String = ""
var n: UInt8 = 0
repeat {
n = try self.read()
if n > Socket.CR { characters.append(Character(UnicodeScalar(n))) }
} while n != Socket.NL
return characters
}
public func peername() throws -> String {
var addr = sockaddr(), len: socklen_t = socklen_t(MemoryLayout<sockaddr>.size)
if getpeername(self.socketFileDescriptor, &addr, &len) != 0 {
throw SocketError.getPeerNameFailed(Errno.description())
}
var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(&addr, len, &hostBuffer, socklen_t(hostBuffer.count), nil, 0, NI_NUMERICHOST) != 0 {
throw SocketError.getNameInfoFailed(Errno.description())
}
return String(cString: hostBuffer)
}
public class func setNoSigPipe(_ socket: Int32) {
#if os(Linux)
// There is no SO_NOSIGPIPE in Linux (nor some other systems). You can instead use the MSG_NOSIGNAL flag when calling send(),
// or use signal(SIGPIPE, SIG_IGN) to make your entire application ignore SIGPIPE.
#else
// Prevents crashes when blocking calls are pending and the app is paused ( via Home button ).
var no_sig_pipe: Int32 = 1
setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &no_sig_pipe, socklen_t(MemoryLayout<Int32>.size))
#endif
}
public class func close(_ socket: Int32) {
#if os(Linux)
let _ = Glibc.close(socket)
#else
let _ = Darwin.close(socket)
#endif
}
}
public func == (socket1: Socket, socket2: Socket) -> Bool {
return socket1.socketFileDescriptor == socket2.socketFileDescriptor
}
|
gpl-3.0
|
d7d13b7c23b8203f5df19f48fac6de2f
| 32.282353 | 137 | 0.602333 | 4.39627 | false | false | false | false |
royhsu/tiny-core
|
Sources/Core/Geometry/Degrees.swift
|
1
|
1653
|
//
// Degrees.swift
// TinyCore
//
// Created by Roy Hsu on 2018/4/5.
// Copyright © 2018 TinyWorld. All rights reserved.
//
// MARK: - Degrees
public struct Degrees: RawRepresentable {
public var rawValue: Double
public init(rawValue: Double) { self.rawValue = rawValue }
}
// MARK: - Numeric
extension Degrees: Numeric {
public init?<T>(exactly source: T) where T: BinaryInteger {
guard
let value = Double(exactly: source)
else { return nil }
self.init(rawValue: value)
}
public init(integerLiteral value: Double) { self.init(rawValue: value) }
public var magnitude: Double { return rawValue.magnitude }
public static func + (
lhs: Degrees,
rhs: Degrees
)
-> Degrees { return Degrees(rawValue: lhs.rawValue + rhs.rawValue) }
public static func += (
lhs: inout Degrees,
rhs: Degrees
) { lhs.rawValue += rhs.rawValue }
public static func - (
lhs: Degrees,
rhs: Degrees
)
-> Degrees { return Degrees(rawValue: lhs.rawValue - rhs.rawValue) }
public static func -= (
lhs: inout Degrees,
rhs: Degrees
) { lhs.rawValue -= rhs.rawValue }
public static func * (
lhs: Degrees,
rhs: Degrees
)
-> Degrees { return Degrees(rawValue: lhs.rawValue * rhs.rawValue) }
public static func *= (
lhs: inout Degrees,
rhs: Degrees
) { lhs.rawValue *= rhs.rawValue }
}
// MARK: - ExpressibleByFloatLiteral
extension Degrees: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) { self.init(rawValue: value) }
}
|
mit
|
98cb147be5d5394bb1ad29be781e0cb4
| 20.179487 | 76 | 0.613196 | 3.92399 | false | false | false | false |
AlexIzh/Griddle
|
CollectionPresenter/UI/TableView/TableHeader.swift
|
1
|
903
|
//
// TableHeader.swift
// CollectionPresenter
//
// Created by Alex on 31/03/16.
// Copyright © 2016 Moqod. All rights reserved.
//
import Foundation
import Griddle
import UIKit
class TableHeader: HeaderFooterView<String> {
override class func size(for model: String, container: UIView) -> CGSize? { return CGSize(width: 0, height: 40) }
lazy var label: UILabel = {
let label = UILabel()
label.textColor = UIColor.black
return label
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
label.frame = bounds
}
override func modelDidChange() {
super.modelDidChange()
label.text = model
}
}
|
mit
|
dcaeab90eaf3d145f20bd423e2fa3f4b
| 22.128205 | 116 | 0.666297 | 4.195349 | false | false | false | false |
aonawale/Passwordless
|
Sources/Passwordless/Middlewares/IdentityProtectionMiddleware.swift
|
1
|
1179
|
import Vapor
import HTTP
import JWT
import Cookies
import AuthProvider
public final class IdentityProtectionMiddleware<T: Parameterizable>: Middleware {
let param: String
let identityKey: String
public init(param: String = T.uniqueSlug, identityKey: String = "sub") {
self.param = param
self.identityKey = identityKey
}
public func respond(to request: HTTP.Request, chainingTo next: Responder) throws -> Response {
guard let bearer = request.auth.header?.bearer else {
throw AuthenticationError.noAuthorizationHeader
}
guard let token = try? JWT(token: bearer.string),
let id = token.payload[identityKey]?.string else {
throw AuthenticationError.invalidBearerAuthorization
}
do {
_ = try token.verifySignature(using: Provider.signer)
} catch {
throw Abort(.unauthorized, reason: Status.unauthorized.reasonPhrase)
}
guard id == request.parameters[param]?.string else {
throw Abort(.unauthorized, reason: Status.unauthorized.reasonPhrase)
}
return try next.respond(to: request)
}
}
|
mit
|
3901d9fc2b5b91d90ba9519587927271
| 30.026316 | 98 | 0.656489 | 4.974684 | false | false | false | false |
bparish628/iFarm-Health
|
iOS/iFarm-Health/Pods/Charts/Source/Charts/Formatters/IndexAxisValueFormatter.swift
|
4
|
1400
|
//
// IndexAxisValueFormatter.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
/// This formatter is used for passing an array of x-axis labels, on whole x steps.
@objc(ChartIndexAxisValueFormatter)
open class IndexAxisValueFormatter: NSObject, IAxisValueFormatter
{
private var _values: [String] = [String]()
private var _valueCount: Int = 0
@objc public var values: [String]
{
get
{
return _values
}
set
{
_values = newValue
_valueCount = _values.count
}
}
public override init()
{
super.init()
}
@objc public init(values: [String])
{
super.init()
self.values = values
}
@objc public static func with(values: [String]) -> IndexAxisValueFormatter?
{
return IndexAxisValueFormatter(values: values)
}
open func stringForValue(_ value: Double,
axis: AxisBase?) -> String
{
let index = Int(value.rounded())
if index < 0 || index >= _valueCount || index != Int(value)
{
return ""
}
return _values[index]
}
}
|
apache-2.0
|
1f54dddd8ff965398794af5409285ee2
| 20.875 | 83 | 0.551429 | 4.545455 | false | false | false | false |
klaus01/Centipede
|
Centipede/UIKit/CE_UIPopoverController.swift
|
1
|
3723
|
//
// CE_UIPopoverController.swift
// Centipede
//
// Created by kelei on 2016/9/15.
// Copyright (c) 2016年 kelei. All rights reserved.
//
import UIKit
extension UIPopoverController {
private struct Static { static var AssociationKey: UInt8 = 0 }
private var _delegate: UIPopoverController_Delegate? {
get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UIPopoverController_Delegate }
set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
private var ce: UIPopoverController_Delegate {
if let obj = _delegate {
return obj
}
if let obj: AnyObject = self.delegate {
if obj is UIPopoverController_Delegate {
return obj as! UIPopoverController_Delegate
}
}
let obj = getDelegateInstance()
_delegate = obj
return obj
}
private func rebindingDelegate() {
let delegate = ce
self.delegate = nil
self.delegate = delegate
}
internal func getDelegateInstance() -> UIPopoverController_Delegate {
return UIPopoverController_Delegate()
}
@discardableResult
public func ce_popoverControllerShouldDismissPopover(handle: @escaping (UIPopoverController) -> Bool) -> Self {
ce._popoverControllerShouldDismissPopover = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_popoverControllerDidDismissPopover(handle: @escaping (UIPopoverController) -> Void) -> Self {
ce._popoverControllerDidDismissPopover = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_popoverController_willRepositionPopoverTo(handle: @escaping (UIPopoverController, UnsafeMutablePointer<CGRect>, AutoreleasingUnsafeMutablePointer<UIView>) -> Void) -> Self {
ce._popoverController_willRepositionPopoverTo = handle
rebindingDelegate()
return self
}
}
internal class UIPopoverController_Delegate: NSObject, UIPopoverControllerDelegate {
var _popoverControllerShouldDismissPopover: ((UIPopoverController) -> Bool)?
var _popoverControllerDidDismissPopover: ((UIPopoverController) -> Void)?
var _popoverController_willRepositionPopoverTo: ((UIPopoverController, UnsafeMutablePointer<CGRect>, AutoreleasingUnsafeMutablePointer<UIView>) -> Void)?
override func responds(to aSelector: Selector!) -> Bool {
let funcDic1: [Selector : Any?] = [
#selector(popoverControllerShouldDismissPopover(_:)) : _popoverControllerShouldDismissPopover,
#selector(popoverControllerDidDismissPopover(_:)) : _popoverControllerDidDismissPopover,
#selector(popoverController(_:willRepositionPopoverTo:in:)) : _popoverController_willRepositionPopoverTo,
]
if let f = funcDic1[aSelector] {
return f != nil
}
return super.responds(to: aSelector)
}
@objc func popoverControllerShouldDismissPopover(_ popoverController: UIPopoverController) -> Bool {
return _popoverControllerShouldDismissPopover!(popoverController)
}
@objc func popoverControllerDidDismissPopover(_ popoverController: UIPopoverController) {
_popoverControllerDidDismissPopover!(popoverController)
}
@objc func popoverController(_ popoverController: UIPopoverController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) {
_popoverController_willRepositionPopoverTo!(popoverController, rect, view)
}
}
|
mit
|
fd1e2a651f25d1afa90bf4950a893b6f
| 38.168421 | 192 | 0.697124 | 5.315714 | false | false | false | false |
victorpimentel/SwiftLint
|
Source/SwiftLintFramework/Rules/TodoRule.swift
|
2
|
3316
|
//
// TodoRule.swift
// SwiftLint
//
// Created by JP Simard on 5/16/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
extension SyntaxKind {
/// Returns if the syntax kind is comment-like.
public var isCommentLike: Bool {
return [
SyntaxKind.comment,
.commentMark,
.commentURL,
.docComment,
.docCommentField
].contains(self)
}
}
public struct TodoRule: ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "todo",
name: "Todo",
description: "TODOs and FIXMEs should be avoided.",
nonTriggeringExamples: [
"// notaTODO:\n",
"// notaFIXME:\n"
],
triggeringExamples: [
"// ↓TODO:\n",
"// ↓FIXME:\n",
"// ↓TODO(note)\n",
"// ↓FIXME(note)\n",
"/* ↓FIXME: */\n",
"/* ↓TODO: */\n",
"/** ↓FIXME: */\n",
"/** ↓TODO: */\n"
]
)
private func customMessage(file: File, range: NSRange) -> String {
var reason = type(of: self).description.description
let offset = NSMaxRange(range)
guard let (lineNumber, _) = file.contents.bridge().lineAndCharacter(forCharacterOffset: offset) else {
return reason
}
let line = file.lines[lineNumber - 1]
// customizing the reason message to be specific to fixme or todo
let violationSubstring = file.contents.bridge().substring(with: range)
let range = NSRange(location: offset, length: NSMaxRange(line.range) - offset)
var message = file.contents.bridge().substring(with: range)
let kind = violationSubstring.hasPrefix("FIXME") ? "FIXMEs" : "TODOs"
// trim whitespace
message = message.trimmingCharacters(in: .whitespacesAndNewlines)
// limiting the output length of todo message
let maxLengthOfMessage = 30
if message.utf16.count > maxLengthOfMessage {
let index = message.index(message.startIndex,
offsetBy: maxLengthOfMessage,
limitedBy: message.endIndex) ?? message.endIndex
message = message.substring(to: index) + "..."
}
if message.isEmpty {
reason = "\(kind) should be avoided."
} else {
reason = "\(kind) should be avoided (\(message))."
}
return reason
}
public func validate(file: File) -> [StyleViolation] {
return file.match(pattern: "\\b(?:TODO|FIXME)(?::|\\b)").flatMap { range, syntaxKinds in
if !syntaxKinds.filter({ !$0.isCommentLike }).isEmpty {
return nil
}
let reason = customMessage(file: file, range: range)
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location),
reason: reason)
}
}
}
|
mit
|
e119add585062dc0d08177ec28d9710a
| 31.663366 | 110 | 0.553198 | 4.823099 | false | false | false | false |
hoanganh6491/Net
|
Net/NetHelper.swift
|
2
|
4725
|
//
// NetHelper.swift
// example
//
// Created by Le Van Nghia on 8/13/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import Foundation
class NetHelper
{
typealias Pair = (String, AnyObject)
/**
* check parameters
*
* @param HttpMethod
*
* @return
*/
class func isQueryParams(method: HttpMethod) -> Bool {
return method == HttpMethod.GET
}
/**
* should send with multi-part if the parameter contains complicated data like image
*
* @param NSDictionary
*
* @return
*/
class func isMultiPart(params: NSDictionary) -> Bool {
var isMultiPart = false
for (_, value) in params {
if value is NetData {
isMultiPart = true
break
}
}
return isMultiPart
}
/**
* get query string with UTF8 encoded from parameters
*
* @param NSDictionary!
*
* @return
*/
class func queryStringFromParams(params: NSDictionary) -> String {
let paramsArray = self.convertParamsToArray(params)
var queryString = join("&", paramsArray.map{"\($0)=\($1)"})
return queryString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
}
/**
* get NSData from parameters
*
* @param NSDictionary!
*
* @return
*/
class func dataFromParams(params: NSDictionary) -> NSData? {
let query = queryStringFromParams(params)
return query.dataUsingEncoding(NSUTF8StringEncoding)
}
/**
* get data for multi-part sending
* http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
*
* @param String
*
* @return
*/
class func dataFromParamsWithBoundary(params: NSDictionary, boundary: String) -> NSData {
var data = NSMutableData()
let prefixString = "--\(boundary)\r\n"
let prefixData = prefixString.dataUsingEncoding(NSUTF8StringEncoding)
let seperatorString = "\r\n"
let seperatorData = seperatorString.dataUsingEncoding(NSUTF8StringEncoding)
let paramsArray = self.convertParamsToArray(params)
for (key, value) in paramsArray {
var valueData: NSData?
var valueType: String?
var filenameClause = ""
if let netData = value as? NetData {
valueData = netData.data
valueType = netData.mimeType.getString()
filenameClause = " filename=\"\(netData.filename)\""
}
else {
let stringValue = "\(value)"
valueData = stringValue.dataUsingEncoding(NSUTF8StringEncoding)
}
// append prefix
data.appendData(prefixData!)
// append content disposition
let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentDispositionData!)
// append content type
if let type = valueType {
let contentTypeString = "Content-Type: \(type)\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentTypeData!)
}
// append data
data.appendData(seperatorData!)
data.appendData(valueData!)
data.appendData(seperatorData!)
}
// append ending data
let endingString = "--\(boundary)--\r\n"
let endingData = endingString.dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(endingData!)
return data
}
private class func convertParamsToArray(params: NSDictionary) -> [Pair] {
var result = [Pair]()
for (key, value) in params {
if let arrayValue = value as? NSArray {
for nestedValue in arrayValue {
let dic = ["\(key)[]": nestedValue]
result += self.convertParamsToArray(dic)
}
}
else if let dicValue = value as? NSDictionary {
for (nestedKey, nestedValue) in dicValue {
let dic = ["\(key)[\(nestedKey)]": nestedValue]
result += self.convertParamsToArray(dic)
}
}
else {
result.append(("\(key)", value))
}
}
return result
}
}
|
mit
|
bf15a4d6cfdc2c41a9eb0cc6abeacd7f
| 29.483871 | 114 | 0.553439 | 5.086114 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/WordPressTest/BlogSettingsDiscussionTests.swift
|
1
|
2912
|
import Foundation
import XCTest
@testable import WordPress
class BlogSettingsDiscussionTests: CoreDataTestCase {
func testCommentsAutoapprovalDisabledEnablesManualModerationFlag() {
let settings = newSettings()
settings.commentsAutoapproval = .disabled
XCTAssertTrue(settings.commentsRequireManualModeration)
XCTAssertFalse(settings.commentsFromKnownUsersAllowlisted)
}
func testCommentsAutoapprovalFromKnownUsersEnablesAllowlistedFlag() {
let settings = newSettings()
settings.commentsAutoapproval = .fromKnownUsers
XCTAssertFalse(settings.commentsRequireManualModeration)
XCTAssertTrue(settings.commentsFromKnownUsersAllowlisted)
}
func testCommentsAutoapprovalEverythingDisablesManualModerationAndAllowlistedFlags() {
let settings = newSettings()
settings.commentsAutoapproval = .everything
XCTAssertFalse(settings.commentsRequireManualModeration)
XCTAssertFalse(settings.commentsFromKnownUsersAllowlisted)
}
func testCommentsSortingSetsTheCorrectCommentSortOrderIntegerValue() {
let settings = newSettings()
settings.commentsSorting = .ascending
XCTAssertTrue(settings.commentsSortOrder?.intValue == Sorting.ascending.rawValue)
settings.commentsSorting = .descending
XCTAssertTrue(settings.commentsSortOrder?.intValue == Sorting.descending.rawValue)
}
func testCommentsSortOrderAscendingSetsTheCorrectCommentSortOrderIntegerValue() {
let settings = newSettings()
settings.commentsSortOrderAscending = true
XCTAssertTrue(settings.commentsSortOrder?.intValue == Sorting.ascending.rawValue)
settings.commentsSortOrderAscending = false
XCTAssertTrue(settings.commentsSortOrder?.intValue == Sorting.descending.rawValue)
}
func testCommentsThreadingDisablesSetsThreadingEnabledFalse() {
let settings = newSettings()
settings.commentsThreading = .disabled
XCTAssertFalse(settings.commentsThreadingEnabled)
}
func testCommentsThreadingEnabledSetsThreadingEnabledTrueAndTheRightDepthValue() {
let settings = newSettings()
settings.commentsThreading = .enabled(depth: 10)
XCTAssertTrue(settings.commentsThreadingEnabled)
XCTAssert(settings.commentsThreadingDepth == 10)
settings.commentsThreading = .enabled(depth: 2)
XCTAssertTrue(settings.commentsThreadingEnabled)
XCTAssert(settings.commentsThreadingDepth == 2)
}
// MARK: - Typealiases
typealias Sorting = BlogSettings.CommentsSorting
// MARK: - Private Helpers
fileprivate func newSettings() -> BlogSettings {
let name = BlogSettings.classNameWithoutNamespaces()
let entity = NSEntityDescription.insertNewObject(forEntityName: name, into: mainContext)
return entity as! BlogSettings
}
}
|
gpl-2.0
|
10aa4079e670a16e1a5664886ab2f47f
| 35.860759 | 96 | 0.750687 | 5.6875 | false | true | false | false |
whiteshadow-gr/HatForIOS
|
HAT/Services/HATFitbitService.swift
|
1
|
14459
|
/**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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 Alamofire
import SwiftyJSON
// MARK: Struct
public struct HATFitbitService {
// MARK: - Get Available fitbit data
/**
Gets all the endpoints from the hat and searches for the fitbit specific ones
- parameter successCallback: A function returning an array of Strings, The endpoints found, and the new token
- parameter errorCallback: A function returning the error occured
*/
public static func getFitbitEndpoints(successCallback: @escaping ([String], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
let url: String = "https://dex.hubofallthings.com/stats/available-data"
HATNetworkHelper.asynchronousRequest(
url,
method: .get,
encoding: Alamofire.URLEncoding.default,
contentType: ContentType.json,
parameters: [:],
headers: [:],
completion: { response in
switch response {
case .error(let error, let statusCode, _):
if error.localizedDescription == "The request timed out." || error.localizedDescription == "The Internet connection appears to be offline." {
errorCallback(.noInternetConnection)
} else {
let message: String = NSLocalizedString("Server responded with error", comment: "")
errorCallback(.generalError(message, statusCode, error))
}
case .isSuccess(let isSuccess, _, let result, let token):
if isSuccess {
if let array: [JSON] = result.array {
for item: JSON in array where item["namespace"] == "fitbit" {
var arraytoReturn: [String] = []
let tempArray: [JSON] = item["endpoints"].arrayValue
for tempItem: JSON in tempArray {
arraytoReturn.append(tempItem["endpoint"].stringValue)
}
successCallback(arraytoReturn, token)
}
} else {
errorCallback(.noValuesFound)
}
}
}
}
)
}
// MARK: - Get Data Generic
/**
The generic function used to get fitbit data
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter namespace: The namespace to read from
- parameter scope: The scope to write from
- parameter parameters: The parameters of the request, limit, take etc.
- parameter successCallback: A ([Object], String?) -> Void function executed on success
- parameter errorCallback: A (HATTableError) -> Void function executed on failure
*/
private static func getGeneric<Object: HATObject>(userDomain: String, userToken: String, namespace: String, scope: String, parameters: Dictionary<String, String>, successCallback: @escaping ([Object], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
func gotResponse(json: [JSON], renewedToken: String?) {
// if we have values return them
if !json.isEmpty {
var arrayToReturn: [Object] = []
for item: JSON in json {
if let object: Object = Object.decode(from: item["data"].dictionaryValue) {
arrayToReturn.append(object)
} else {
print("error parsing json")
}
}
successCallback(arrayToReturn, renewedToken)
} else {
errorCallback(.noValuesFound)
}
}
HATAccountService.getHatTableValues(
token: userToken,
userDomain: userDomain,
namespace: namespace,
scope: scope,
parameters: parameters,
successCallback: gotResponse,
errorCallback: errorCallback)
}
// MARK: - Get Data
/**
Gets fitbit sleep from HAT
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter parameters: The parameters of the request, limit, take etc.
- parameter successCallback: A ([HATFitbitSleepObject], String?) -> Void function executed on success
- parameter errorCallback: A (HATTableError) -> Void function executed on failure
*/
public static func getSleep(userDomain: String, userToken: String, parameters: Dictionary<String, String>, successCallback: @escaping ([HATFitbitSleep], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
HATFitbitService.getGeneric(
userDomain: userDomain,
userToken: userToken,
namespace: "fitbit",
scope: "sleep",
parameters: parameters,
successCallback: successCallback,
errorCallback: errorCallback)
}
/**
Gets fitbit weight from HAT
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter parameters: The parameters of the request, limit, take etc.
- parameter successCallback: A ([HATFitbitWeightObject], String?) -> Void function executed on success
- parameter errorCallback: A (HATTableError) -> Void function executed on failure
*/
public static func getWeight(userDomain: String, userToken: String, parameters: Dictionary<String, String>, successCallback: @escaping ([HATFitbitWeight], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
HATFitbitService.getGeneric(
userDomain: userDomain,
userToken: userToken,
namespace: "fitbit",
scope: "weight",
parameters: parameters,
successCallback: successCallback,
errorCallback: errorCallback)
}
/**
Gets fitbit profile from HAT
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter parameters: The parameters of the request, limit, take etc.
- parameter successCallback: A ([HATFitbitProfileObject], String?) -> Void function executed on success
- parameter errorCallback: A (HATTableError) -> Void function executed on failure
*/
public static func getProfile(userDomain: String, userToken: String, parameters: Dictionary<String, String>, successCallback: @escaping ([HATFitbitProfile], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
HATFitbitService.getGeneric(
userDomain: userDomain,
userToken: userToken,
namespace: "fitbit",
scope: "profile",
parameters: parameters,
successCallback: successCallback,
errorCallback: errorCallback)
}
/**
Gets fitbit activity from HAT
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter parameters: The parameters of the request, limit, take etc.
- parameter successCallback: A ([HATFitbitDailyActivityObject], String?) -> Void function executed on success
- parameter errorCallback: A (HATTableError) -> Void function executed on failure
*/
public static func getDailyActivity(userDomain: String, userToken: String, parameters: Dictionary<String, String>, successCallback: @escaping ([HATFitbitDailyActivity], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
HATFitbitService.getGeneric(
userDomain: userDomain,
userToken: userToken,
namespace: "fitbit",
scope: "activity/day/summary",
parameters: parameters,
successCallback: successCallback,
errorCallback: errorCallback)
}
/**
Gets fitbit lifetime stats from HAT
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter parameters: The parameters of the request, limit, take etc.
- parameter successCallback: A ([HATFitbitStatsObject], String?) -> Void function executed on success
- parameter errorCallback: A (HATTableError) -> Void function executed on failure
*/
public static func getLifetimeStats(userDomain: String, userToken: String, parameters: Dictionary<String, String>, successCallback: @escaping ([HATFitbitStats], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
HATFitbitService.getGeneric(
userDomain: userDomain,
userToken: userToken,
namespace: "fitbit",
scope: "lifetime/stats",
parameters: parameters,
successCallback: successCallback,
errorCallback: errorCallback)
}
/**
Gets fitbit activity from HAT
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter parameters: The parameters of the request, limit, take etc.
- parameter successCallback: A ([HATFitbitActivityObject], String?) -> Void function executed on success
- parameter errorCallback: A (HATTableError) -> Void function executed on failure
*/
public static func getActivity(userDomain: String, userToken: String, parameters: Dictionary<String, String>, successCallback: @escaping ([HATFitbitActivity], String?) -> Void, errorCallback: @escaping (HATTableError) -> Void) {
HATFitbitService.getGeneric(
userDomain: userDomain,
userToken: userToken,
namespace: "fitbit",
scope: "activity",
parameters: parameters,
successCallback: successCallback,
errorCallback: errorCallback)
}
// MARK: - Check if Fitbit is enabled
/**
Checks if Fitbit plug is enabled
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter plugURL: The plug's url returned from HAT
- parameter statusURL: The plug's status url
- parameter successCallback: A (Bool, String?) -> Void function executed on success
- parameter errorCallback: A (JSONParsingError) -> Void function executed on failure
*/
public static func checkIfFitbitIsEnabled(userDomain: String, userToken: String, plugURL: String, statusURL: String, successCallback: @escaping (Bool, String?) -> Void, errorCallback: @escaping (JSONParsingError) -> Void) {
func gotToken(fitbitToken: String, newUserToken: String?) {
// construct the url, set parameters and headers for the request
let parameters: Dictionary<String, String> = [:]
let headers: [String: String] = [RequestHeaders.xAuthToken: fitbitToken]
// make the request
HATNetworkHelper.asynchronousRequest(statusURL, method: .get, encoding: Alamofire.URLEncoding.default, contentType: ContentType.json, parameters: parameters, headers: headers, completion: {(response: HATNetworkHelper.ResultType) -> Void in
// act upon response
switch response {
case .isSuccess(_, let statusCode, _, _):
if statusCode == 200 {
successCallback(true, fitbitToken)
} else {
successCallback(false, fitbitToken)
}
// inform user that there was an error
case .error(let error, let statusCode, _):
if statusCode == 403 {
successCallback(false, fitbitToken)
}
let message: String = NSLocalizedString("Server responded with error", comment: "")
errorCallback(.generalError(message, statusCode, error))
}
})
}
HATFitbitService.getApplicationTokenForFitbit(
userDomain: userDomain,
userToken: userToken,
dataPlugURL: plugURL,
successCallback: gotToken,
errorCallback: errorCallback)
}
// MARK: - Get Fitbit token
/**
Gets fitbit token
- parameter userDomain: The user's domain
- parameter userToken: The user's token
- parameter dataPlugURL: The plug's url returned from HAT
- parameter successCallback: A (String, String?) -> Void function executed on success
- parameter errorCallback: A (JSONParsingError) -> Void function executed on failure
*/
public static func getApplicationTokenForFitbit(userDomain: String, userToken: String, dataPlugURL: String, successCallback: @escaping (String, String?) -> Void, errorCallback: @escaping (JSONParsingError) -> Void) {
HATService.getApplicationTokenLegacyFor(
serviceName: Fitbit.source,
userDomain: userDomain,
userToken: userToken,
resource: dataPlugURL,
succesfulCallBack: successCallback,
failCallBack: errorCallback)
}
}
|
mpl-2.0
|
1b86d296d3455ea11df408a91485adb4
| 41.778107 | 274 | 0.580953 | 5.608611 | false | false | false | false |
radvansky-tomas/NutriFacts
|
nutri-facts/nutri-facts/Helpers/Globals.swift
|
1
|
30732
|
// Created by Tomas Radvansky on 21/01/2015.
// Copyright (c) 2015 Tomas Radvansky. All rights reserved.//
import UIKit
//Icomoon enumeration
enum MoonIcons:String {case home = "\u{e900}"
case home2 = "\u{e901}"
case home3 = "\u{e902}"
case office = "\u{e903}"
case newspaper = "\u{e904}"
case pencil = "\u{e905}"
case pencil2 = "\u{e906}"
case quill = "\u{e907}"
case pen = "\u{e908}"
case blog = "\u{e909}"
case eyedropper = "\u{e90a}"
case droplet = "\u{e90b}"
case paint_format = "\u{e90c}"
case image = "\u{e90d}"
case images = "\u{e90e}"
case camera = "\u{e90f}"
case headphones = "\u{e910}"
case music = "\u{e911}"
case play = "\u{e912}"
case film = "\u{e913}"
case video_camera = "\u{e914}"
case dice = "\u{e915}"
case pacman = "\u{e916}"
case spades = "\u{e917}"
case clubs = "\u{e918}"
case diamonds = "\u{e919}"
case bullhorn = "\u{e91a}"
case connection = "\u{e91b}"
case podcast = "\u{e91c}"
case feed = "\u{e91d}"
case mic = "\u{e91e}"
case book = "\u{e91f}"
case books = "\u{e920}"
case library = "\u{e921}"
case file_text = "\u{e922}"
case profile = "\u{e923}"
case file_empty = "\u{e924}"
case files_empty = "\u{e925}"
case file_text2 = "\u{e926}"
case file_picture = "\u{e927}"
case file_music = "\u{e928}"
case file_play = "\u{e929}"
case file_video = "\u{e92a}"
case file_zip = "\u{e92b}"
case copy = "\u{e92c}"
case paste = "\u{e92d}"
case stack = "\u{e92e}"
case folder = "\u{e92f}"
case folder_open = "\u{e930}"
case folder_plus = "\u{e931}"
case folder_minus = "\u{e932}"
case folder_download = "\u{e933}"
case folder_upload = "\u{e934}"
case price_tag = "\u{e935}"
case price_tags = "\u{e936}"
case barcode = "\u{e937}"
case qrcode = "\u{e938}"
case ticket = "\u{e939}"
case cart = "\u{e93a}"
case coin_dollar = "\u{e93b}"
case coin_euro = "\u{e93c}"
case coin_pound = "\u{e93d}"
case coin_yen = "\u{e93e}"
case credit_card = "\u{e93f}"
case calculator = "\u{e940}"
case lifebuoy = "\u{e941}"
case phone = "\u{e942}"
case phone_hang_up = "\u{e943}"
case address_book = "\u{e944}"
case envelop = "\u{e945}"
case pushpin = "\u{e946}"
case location = "\u{e947}"
case location2 = "\u{e948}"
case compass = "\u{e949}"
case compass2 = "\u{e94a}"
case map = "\u{e94b}"
case map2 = "\u{e94c}"
case history = "\u{e94d}"
case clock = "\u{e94e}"
case clock2 = "\u{e94f}"
case alarm = "\u{e950}"
case bell = "\u{e951}"
case stopwatch = "\u{e952}"
case calendar = "\u{e953}"
case printer = "\u{e954}"
case keyboard = "\u{e955}"
case display = "\u{e956}"
case laptop = "\u{e957}"
case mobile = "\u{e958}"
case mobile2 = "\u{e959}"
case tablet = "\u{e95a}"
case tv = "\u{e95b}"
case drawer = "\u{e95c}"
case drawer2 = "\u{e95d}"
case box_add = "\u{e95e}"
case box_remove = "\u{e95f}"
case download = "\u{e960}"
case upload = "\u{e961}"
case floppy_disk = "\u{e962}"
case drive = "\u{e963}"
case database = "\u{e964}"
case undo = "\u{e965}"
case redo = "\u{e966}"
case undo2 = "\u{e967}"
case redo2 = "\u{e968}"
case forward = "\u{e969}"
case reply = "\u{e96a}"
case bubble = "\u{e96b}"
case bubbles = "\u{e96c}"
case bubbles2 = "\u{e96d}"
case bubble2 = "\u{e96e}"
case bubbles3 = "\u{e96f}"
case bubbles4 = "\u{e970}"
case user = "\u{e971}"
case users = "\u{e972}"
case user_plus = "\u{e973}"
case user_minus = "\u{e974}"
case user_check = "\u{e975}"
case user_tie = "\u{e976}"
case quotes_left = "\u{e977}"
case quotes_right = "\u{e978}"
case hour_glass = "\u{e979}"
case spinner = "\u{e97a}"
case spinner2 = "\u{e97b}"
case spinner3 = "\u{e97c}"
case spinner4 = "\u{e97d}"
case spinner5 = "\u{e97e}"
case spinner6 = "\u{e97f}"
case spinner7 = "\u{e980}"
case spinner8 = "\u{e981}"
case spinner9 = "\u{e982}"
case spinner10 = "\u{e983}"
case spinner11 = "\u{e984}"
case binoculars = "\u{e985}"
case search = "\u{e986}"
case zoom_in = "\u{e987}"
case zoom_out = "\u{e988}"
case enlarge = "\u{e989}"
case shrink = "\u{e98a}"
case enlarge2 = "\u{e98b}"
case shrink2 = "\u{e98c}"
case key = "\u{e98d}"
case key2 = "\u{e98e}"
case lock = "\u{e98f}"
case unlocked = "\u{e990}"
case wrench = "\u{e991}"
case equalizer = "\u{e992}"
case equalizer2 = "\u{e993}"
case cog = "\u{e994}"
case cogs = "\u{e995}"
case hammer = "\u{e996}"
case magic_wand = "\u{e997}"
case aid_kit = "\u{e998}"
case bug = "\u{e999}"
case pie_chart = "\u{e99a}"
case stats_dots = "\u{e99b}"
case stats_bars = "\u{e99c}"
case stats_bars2 = "\u{e99d}"
case trophy = "\u{e99e}"
case gift = "\u{e99f}"
case glass = "\u{e9a0}"
case glass2 = "\u{e9a1}"
case mug = "\u{e9a2}"
case spoon_knife = "\u{e9a3}"
case leaf = "\u{e9a4}"
case rocket = "\u{e9a5}"
case meter = "\u{e9a6}"
case meter2 = "\u{e9a7}"
case hammer2 = "\u{e9a8}"
case fire = "\u{e9a9}"
case lab = "\u{e9aa}"
case magnet = "\u{e9ab}"
case bin = "\u{e9ac}"
case bin2 = "\u{e9ad}"
case briefcase = "\u{e9ae}"
case airplane = "\u{e9af}"
case truck = "\u{e9b0}"
case road = "\u{e9b1}"
case accessibility = "\u{e9b2}"
case target = "\u{e9b3}"
case shield = "\u{e9b4}"
case power = "\u{e9b5}"
case power_cord = "\u{e9b7}"
case clipboard = "\u{e9b8}"
case list_numbered = "\u{e9b9}"
case list = "\u{e9ba}"
case list2 = "\u{e9bb}"
case tree = "\u{e9bc}"
case menu = "\u{e9bd}"
case menu2 = "\u{e9be}"
case menu3 = "\u{e9bf}"
case menu4 = "\u{e9c0}"
case cloud = "\u{e9c1}"
case cloud_download = "\u{e9c2}"
case cloud_upload = "\u{e9c3}"
case cloud_check = "\u{e9c4}"
case download2 = "\u{e9c5}"
case upload2 = "\u{e9c6}"
case download3 = "\u{e9c7}"
case upload3 = "\u{e9c8}"
case sphere = "\u{e9c9}"
case earth = "\u{e9ca}"
case link = "\u{e9cb}"
case flag = "\u{e9cc}"
case attachment = "\u{e9cd}"
case eye = "\u{e9ce}"
case eye_plus = "\u{e9cf}"
case eye_minus = "\u{e9d0}"
case eye_blocked = "\u{e9d1}"
case bookmark = "\u{e9d2}"
case bookmarks = "\u{e9d3}"
case sun = "\u{e9d4}"
case contrast = "\u{e9d5}"
case brightness_contrast = "\u{e9d6}"
case star_empty = "\u{e9d7}"
case star_half = "\u{e9d8}"
case star_full = "\u{e9d9}"
case heart = "\u{e9da}"
case heart_broken = "\u{e9db}"
case man = "\u{e9dc}"
case woman = "\u{e9dd}"
case man_woman = "\u{e9de}"
case happy = "\u{e9df}"
case happy2 = "\u{e9e0}"
case smile = "\u{e9e1}"
case smile2 = "\u{e9e2}"
case tongue = "\u{e9e3}"
case tongue2 = "\u{e9e4}"
case sad = "\u{e9e5}"
case sad2 = "\u{e9e6}"
case wink = "\u{e9e7}"
case wink2 = "\u{e9e8}"
case grin = "\u{e9e9}"
case grin2 = "\u{e9ea}"
case cool = "\u{e9eb}"
case cool2 = "\u{e9ec}"
case angry = "\u{e9ed}"
case angry2 = "\u{e9ee}"
case evil = "\u{e9ef}"
case evil2 = "\u{e9f0}"
case shocked = "\u{e9f1}"
case shocked2 = "\u{e9f2}"
case baffled = "\u{e9f3}"
case baffled2 = "\u{e9f4}"
case confused = "\u{e9f5}"
case confused2 = "\u{e9f6}"
case neutral = "\u{e9f7}"
case neutral2 = "\u{e9f8}"
case hipster = "\u{e9f9}"
case hipster2 = "\u{e9fa}"
case wondering = "\u{e9fb}"
case wondering2 = "\u{e9fc}"
case sleepy = "\u{e9fd}"
case sleepy2 = "\u{e9fe}"
case frustrated = "\u{e9ff}"
case frustrated2 = "\u{ea00}"
case crying = "\u{ea01}"
case crying2 = "\u{ea02}"
case point_up = "\u{ea03}"
case point_right = "\u{ea04}"
case point_down = "\u{ea05}"
case point_left = "\u{ea06}"
case warning = "\u{ea07}"
case notification = "\u{ea08}"
case question = "\u{ea09}"
case plus = "\u{ea0a}"
case minus = "\u{ea0b}"
case info = "\u{ea0c}"
case cancel_circle = "\u{ea0d}"
case blocked = "\u{ea0e}"
case cross = "\u{ea0f}"
case checkmark = "\u{ea10}"
case checkmark2 = "\u{ea11}"
case spell_check = "\u{ea12}"
case enter = "\u{ea13}"
case exit = "\u{ea14}"
case play2 = "\u{ea15}"
case pause = "\u{ea16}"
case stop = "\u{ea17}"
case previous = "\u{ea18}"
case next = "\u{ea19}"
case backward = "\u{ea1a}"
case forward2 = "\u{ea1b}"
case play3 = "\u{ea1c}"
case pause2 = "\u{ea1d}"
case stop2 = "\u{ea1e}"
case backward2 = "\u{ea1f}"
case forward3 = "\u{ea20}"
case first = "\u{ea21}"
case last = "\u{ea22}"
case previous2 = "\u{ea23}"
case next2 = "\u{ea24}"
case eject = "\u{ea25}"
case volume_high = "\u{ea26}"
case volume_medium = "\u{ea27}"
case volume_low = "\u{ea28}"
case volume_mute = "\u{ea29}"
case volume_mute2 = "\u{ea2a}"
case volume_increase = "\u{ea2b}"
case volume_decrease = "\u{ea2c}"
case loop = "\u{ea2d}"
case loop2 = "\u{ea2e}"
case infinite = "\u{ea2f}"
case shuffle = "\u{ea30}"
case arrow_up_left = "\u{ea31}"
case arrow_up = "\u{ea32}"
case arrow_up_right = "\u{ea33}"
case arrow_right = "\u{ea34}"
case arrow_down_right = "\u{ea35}"
case arrow_down = "\u{ea36}"
case arrow_down_left = "\u{ea37}"
case arrow_left = "\u{ea38}"
case arrow_up_left2 = "\u{ea39}"
case arrow_up2 = "\u{ea3a}"
case arrow_up_right2 = "\u{ea3b}"
case arrow_right2 = "\u{ea3c}"
case arrow_down_right2 = "\u{ea3d}"
case arrow_down2 = "\u{ea3e}"
case arrow_down_left2 = "\u{ea3f}"
case arrow_left2 = "\u{ea40}"
case circle_up = "\u{ea41}"
case circle_right = "\u{ea42}"
case circle_down = "\u{ea43}"
case circle_left = "\u{ea44}"
case tab = "\u{ea45}"
case move_up = "\u{ea46}"
case move_down = "\u{ea47}"
case sort_alpha_asc = "\u{ea48}"
case sort_alpha_desc = "\u{ea49}"
case sort_numeric_asc = "\u{ea4a}"
case sort_numberic_desc = "\u{ea4b}"
case sort_amount_asc = "\u{ea4c}"
case sort_amount_desc = "\u{ea4d}"
case command = "\u{ea4e}"
case shift = "\u{ea4f}"
case ctrl = "\u{ea50}"
case opt = "\u{ea51}"
case checkbox_checked = "\u{ea52}"
case checkbox_unchecked = "\u{ea53}"
case radio_checked = "\u{ea54}"
case radio_checked2 = "\u{ea55}"
case radio_unchecked = "\u{ea56}"
case crop = "\u{ea57}"
case make_group = "\u{ea58}"
case ungroup = "\u{ea59}"
case scissors = "\u{ea5a}"
case filter = "\u{ea5b}"
case font = "\u{ea5c}"
case ligature = "\u{ea5d}"
case ligature2 = "\u{ea5e}"
case text_height = "\u{ea5f}"
case text_width = "\u{ea60}"
case font_size = "\u{ea61}"
case bold = "\u{ea62}"
case underline = "\u{ea63}"
case italic = "\u{ea64}"
case strikethrough = "\u{ea65}"
case omega = "\u{ea66}"
case sigma = "\u{ea67}"
case page_break = "\u{ea68}"
case superscript = "\u{ea69}"
case superscript2 = "\u{ea6b}"
case subscript2 = "\u{ea6c}"
case text_color = "\u{ea6d}"
case pagebreak = "\u{ea6e}"
case clear_formatting = "\u{ea6f}"
case table = "\u{ea70}"
case table2 = "\u{ea71}"
case insert_template = "\u{ea72}"
case pilcrow = "\u{ea73}"
case ltr = "\u{ea74}"
case rtl = "\u{ea75}"
case section = "\u{ea76}"
case paragraph_left = "\u{ea77}"
case paragraph_center = "\u{ea78}"
case paragraph_right = "\u{ea79}"
case paragraph_justify = "\u{ea7a}"
case indent_increase = "\u{ea7b}"
case indent_decrease = "\u{ea7c}"
case share = "\u{ea7d}"
case new_tab = "\u{ea7e}"
case embed = "\u{ea7f}"
case embed2 = "\u{ea80}"
case terminal = "\u{ea81}"
case share2 = "\u{ea82}"
case mail = "\u{ea83}"
case mail2 = "\u{ea84}"
case mail3 = "\u{ea85}"
case mail4 = "\u{ea86}"
case google = "\u{ea87}"
case google_plus = "\u{ea88}"
case google_plus2 = "\u{ea89}"
case google_plus3 = "\u{ea8a}"
case google_drive = "\u{ea8b}"
case facebook = "\u{ea8c}"
case facebook2 = "\u{ea8d}"
case facebook3 = "\u{ea8e}"
case ello = "\u{ea8f}"
case instagram = "\u{ea90}"
case twitter = "\u{ea91}"
case twitter2 = "\u{ea92}"
case twitter3 = "\u{ea93}"
case feed2 = "\u{ea94}"
case feed3 = "\u{ea95}"
case feed4 = "\u{ea96}"
case youtube = "\u{ea97}"
case youtube2 = "\u{ea98}"
case youtube3 = "\u{ea99}"
case youtube4 = "\u{ea9a}"
case twitch = "\u{ea9b}"
case vimeo = "\u{ea9c}"
case vimeo2 = "\u{ea9d}"
case vimeo3 = "\u{ea9e}"
case lanyrd = "\u{ea9f}"
case flickr = "\u{eaa0}"
case flickr2 = "\u{eaa1}"
case flickr3 = "\u{eaa2}"
case flickr4 = "\u{eaa3}"
case picassa = "\u{eaa4}"
case picassa2 = "\u{eaa5}"
case dribbble = "\u{eaa6}"
case dribbble2 = "\u{eaa7}"
case dribbble3 = "\u{eaa8}"
case forrst = "\u{eaa9}"
case forrst2 = "\u{eaaa}"
case deviantart = "\u{eaab}"
case deviantart2 = "\u{eaac}"
case steam = "\u{eaad}"
case steam2 = "\u{eaae}"
case dropbox = "\u{eaaf}"
case onedrive = "\u{eab0}"
case github = "\u{eab1}"
case github2 = "\u{eab2}"
case github3 = "\u{eab3}"
case github4 = "\u{eab4}"
case github5 = "\u{eab5}"
case wordpress = "\u{eab6}"
case wordpress2 = "\u{eab7}"
case joomla = "\u{eab8}"
case blogger = "\u{eab9}"
case blogger2 = "\u{eaba}"
case tumblr = "\u{eabb}"
case tumblr2 = "\u{eabc}"
case yahoo = "\u{eabd}"
case tux = "\u{eabe}"
case apple = "\u{eabf}"
case finder = "\u{eac0}"
case android = "\u{eac1}"
case windows = "\u{eac2}"
case windows8 = "\u{eac3}"
case soundcloud = "\u{eac4}"
case soundcloud2 = "\u{eac5}"
case skype = "\u{eac6}"
case reddit = "\u{eac7}"
case linkedin = "\u{eac8}"
case linkedin2 = "\u{eac9}"
case lastfm = "\u{eaca}"
case lastfm2 = "\u{eacb}"
case delicious = "\u{eacc}"
case stumbleupon = "\u{eacd}"
case stumbleupon2 = "\u{eace}"
case stackoverflow = "\u{eacf}"
case pinterest = "\u{ead0}"
case pinterest2 = "\u{ead1}"
case xing = "\u{ead2}"
case xing2 = "\u{ead3}"
case flattr = "\u{ead4}"
case foursquare = "\u{ead5}"
case paypal = "\u{ead6}"
case paypal2 = "\u{ead7}"
case paypal3 = "\u{ead8}"
case yelp = "\u{ead9}"
case file_pdf = "\u{eada}"
case file_openoffice = "\u{eadb}"
case file_word = "\u{eadc}"
case file_excel = "\u{eadd}"
case libreoffice = "\u{eade}"
case html5 = "\u{eadf}"
case html52 = "\u{eae0}"
case css3 = "\u{eae1}"
case git = "\u{eae2}"
case svg = "\u{eae3}"
case codepen = "\u{eae4}"
case chrome = "\u{eae5}"
case firefox = "\u{eae6}"
case IE = "\u{eae7}"
case opera = "\u{eae8}"
case safari = "\u{eae9}"
case IcoMoon = "\u{eaea}"
case refresh = "\u{e600}"
case addPeople = "\u{e601}"
case testAttraction = "\u{e608}"
case backMenu = "\u{e609}"
case unchecked = "\u{e60a}"
case checked = "\u{e60b}"
case unknownchecked = "\u{e60c}"
case calendar2 = "\u{e60d}"
case messages = "\u{e60e}"
case check = "\u{e60f}"
case check2 = "\u{e610}"
case people = "\u{e612}"
case credits = "\u{e613}"
case edit = "\u{e616}"
case fb = "\u{e617}"
case flashpic = "\u{e618}"
case delete = "\u{e619}"
case gifts = "\u{e61a}"
case attraction1 = "\u{e61b}"
case attraction2 = "\u{e61c}"
case kiss = "\u{e61d}"
case back = "\u{e61e}"
case lock3 = "\u{e620}"
case lock2 = "\u{e621}"
case mapMarker = "\u{e622}"
case exit2 = "\u{e623}"
case sidemenu = "\u{e624}"
case rightArrowMenu = "\u{e626}"
case uniE627 = "\u{e627}"
case newMessage = "\u{e628}"
case user1 = "\u{e629}"
case camera1 = "\u{e62a}"
case uniE62B = "\u{e62b}"
case uniE62C = "\u{e62c}"
case bin3 = "\u{e62d}"
case deletePeople = "\u{e62e}"
case rightArrow = "\u{e630}"
case download4 = "\u{e631}"
case save = "\u{e632}"
case searchMenu = "\u{e633}"
case seach2 = "\u{e634}"
case lockmenu = "\u{e635}"
case settings = "\u{e636}"
case wine = "\u{e637}"
case time = "\u{e638}"
case male = "\u{e639}"
case female = "\u{e63a}"
case vip = "\u{e63b}"
case visits = "\u{e63c}"
case webcam = "\u{e63d}"
case lock1 = "\u{e63e}"
case lockChecked = "\u{e643}"
case pending = "\u{e644}"
case boosts = "\u{e645}"
case invisible = "\u{e646}"
case doubleAttraction = "\u{e61b}\u{e61c}"
static let allValues = [home,
home2,
home3,
office,
newspaper,
pencil,
pencil2,
quill,
pen,
blog,
eyedropper,
droplet,
paint_format,
image,
images,
camera,
headphones,
music,
play,
film,
video_camera,
dice,
pacman,
spades,
clubs,
diamonds,
bullhorn,
connection,
podcast,
feed,
mic,
book,
books,
library,
file_text,
profile,
file_empty,
files_empty,
file_text2,
file_picture,
file_music,
file_play,
file_video,
file_zip,
copy,
paste,
stack,
folder,
folder_open,
folder_plus,
folder_minus,
folder_download,
folder_upload,
price_tag,
price_tags,
barcode,
qrcode,
ticket,
cart,
coin_dollar,
coin_euro,
coin_pound,
coin_yen,
credit_card,
calculator,
lifebuoy,
phone,
phone_hang_up,
address_book,
envelop,
pushpin,
location,
location2,
compass,
compass2,
map,
map2,
history,
clock,
clock2,
alarm,
bell,
stopwatch,
calendar,
printer,
keyboard,
display,
laptop,
mobile,
mobile2,
tablet,
tv,
drawer,
drawer2,
box_add,
box_remove,
download,
upload,
floppy_disk,
drive,
database,
undo,
redo,
undo2,
redo2,
forward,
reply,
bubble,
bubbles,
bubbles2,
bubble2,
bubbles3,
bubbles4,
user,
users,
user_plus,
user_minus,
user_check,
user_tie,
quotes_left,
quotes_right,
hour_glass,
spinner,
spinner2,
spinner3,
spinner4,
spinner5,
spinner6,
spinner7,
spinner8,
spinner9,
spinner10,
spinner11,
binoculars,
search,
zoom_in,
zoom_out,
enlarge,
shrink,
enlarge2,
shrink2,
key,
key2,
lock,
unlocked,
wrench,
equalizer,
equalizer2,
cog,
cogs,
hammer,
magic_wand,
aid_kit,
bug,
pie_chart,
stats_dots,
stats_bars,
stats_bars2,
trophy,
gift,
glass,
glass2,
mug,
spoon_knife,
leaf,
rocket,
meter,
meter2,
hammer2,
fire,
lab,
magnet,
bin,
bin2,
briefcase,
airplane,
truck,
road,
accessibility,
target,
shield,
power,
power_cord,
clipboard,
list_numbered,
list,
list2,
tree,
menu,
menu2,
menu3,
menu4,
cloud,
cloud_download,
cloud_upload,
cloud_check,
download2,
upload2,
download3,
upload3,
sphere,
earth,
link,
flag,
attachment,
eye,
eye_plus,
eye_minus,
eye_blocked,
bookmark,
bookmarks,
sun,
contrast,
brightness_contrast,
star_empty,
star_half,
star_full,
heart,
heart_broken,
man,
woman,
man_woman,
happy,
happy2,
smile,
smile2,
tongue,
tongue2,
sad,
sad2,
wink,
wink2,
grin,
grin2,
cool,
cool2,
angry,
angry2,
evil,
evil2,
shocked,
shocked2,
baffled,
baffled2,
confused,
confused2,
neutral,
neutral2,
hipster,
hipster2,
wondering,
wondering2,
sleepy,
sleepy2,
frustrated,
frustrated2,
crying,
crying2,
point_up,
point_right,
point_down,
point_left,
warning,
notification,
question,
plus,
minus,
info,
cancel_circle,
blocked,
cross,
checkmark,
checkmark2,
spell_check,
enter,
exit,
play2,
pause,
stop,
previous,
next,
backward,
forward2,
play3,
pause2,
stop2,
backward2,
forward3,
first,
last,
previous2,
next2,
eject,
volume_high,
volume_medium,
volume_low,
volume_mute,
volume_mute2,
volume_increase,
volume_decrease,
loop,
loop2,
infinite,
shuffle,
arrow_up_left,
arrow_up,
arrow_up_right,
arrow_right,
arrow_down_right,
arrow_down,
arrow_down_left,
arrow_left,
arrow_up_left2,
arrow_up2,
arrow_up_right2,
arrow_right2,
arrow_down_right2,
arrow_down2,
arrow_down_left2,
arrow_left2,
circle_up,
circle_right,
circle_down,
circle_left,
tab,
move_up,
move_down,
sort_alpha_asc,
sort_alpha_desc,
sort_numeric_asc,
sort_numberic_desc,
sort_amount_asc,
sort_amount_desc,
command,
shift,
ctrl,
opt,
checkbox_checked,
checkbox_unchecked,
radio_checked,
radio_checked2,
radio_unchecked,
crop,
make_group,
ungroup,
scissors,
filter,
font,
ligature,
ligature2,
text_height,
text_width,
font_size,
bold,
underline,
italic,
strikethrough,
omega,
sigma,
page_break,
superscript,
superscript2,
subscript2,
text_color,
pagebreak,
clear_formatting,
table,
table2,
insert_template,
pilcrow,
ltr,
rtl,
section,
paragraph_left,
paragraph_center,
paragraph_right,
paragraph_justify,
indent_increase,
indent_decrease,
share,
new_tab,
embed,
embed2,
terminal,
share2,
mail,
mail2,
mail3,
mail4,
google,
google_plus,
google_plus2,
google_plus3,
google_drive,
facebook,
facebook2,
facebook3,
ello,
instagram,
twitter,
twitter2,
twitter3,
feed2,
feed3,
feed4,
youtube,
youtube2,
youtube3,
youtube4,
twitch,
vimeo,
vimeo2,
vimeo3,
lanyrd,
flickr,
flickr2,
flickr3,
flickr4,
picassa,
picassa2,
dribbble,
dribbble2,
dribbble3,
forrst,
forrst2,
deviantart,
deviantart2,
steam,
steam2,
dropbox,
onedrive,
github,
github2,
github3,
github4,
github5,
wordpress,
wordpress2,
joomla,
blogger,
blogger2,
tumblr,
tumblr2,
yahoo,
tux,
apple,
finder,
android,
windows,
windows8,
soundcloud,
soundcloud2,
skype,
reddit,
linkedin,
linkedin2,
lastfm,
lastfm2,
delicious,
stumbleupon,
stumbleupon2,
stackoverflow,
pinterest,
pinterest2,
xing,
xing2,
flattr,
foursquare,
paypal,
paypal2,
paypal3,
yelp,
file_pdf,
file_openoffice,
file_word,
file_excel,
libreoffice,
html5,
html52,
css3,
git,
svg,
codepen,
chrome,
firefox,
IE,
opera,
safari,
IcoMoon,
refresh,
addPeople,
testAttraction,
backMenu,
unchecked,
checked,
unknownchecked,
calendar2,
messages,
check,
check2,
people,
credits,
edit,
fb,
flashpic,
delete,
gifts,
attraction1,
attraction2,
kiss,
back,
lock3,
lock2,
mapMarker,
exit2,
sidemenu,
rightArrowMenu,
uniE627,
newMessage,
user1,
camera1,
uniE62B,
uniE62C,
bin3,
deletePeople,
rightArrow,
download4,
save,
searchMenu,
seach2,
lockmenu,
settings,
wine,
time,
male,
female,
vip,
visits,
webcam,
lock1,
lockChecked,
pending,
boosts,
invisible,
doubleAttraction]
}
//MARK: Daily income per item
let RTotalFat:Int = 65 //(g)
let RSaturatedFat:Int = 20 //g
let RCholesterol:Int = 300 //milligrams (mg)
let RSodium:Double = 2.4 //mg
let RPotassium:Double = 3.5 //mg
let RTotalCarbohydrate:Int = 300 //g
let RDietaryFiber:Int = 25 //g
let RProtein:Int = 50 //g
//Vitamin A 5,000 International Units (IU)
//Vitamin C 60 mg
//Calcium 1,000 mg
//Iron 18 mg
//Vitamin D 400 IU
//Vitamin E 30 IU
//Vitamin K 80 micrograms µg
//Thiamin 1.5 mg
//Riboflavin 1.7 mg
//Niacin 20 mg
//Vitamin B6 2 mg
//Folate 400 µg
//Vitamin B12 6 µg
//Biotin 300 µg
//Pantothenic acid 10 mg
//Phosphorus 1,000 mg
//Iodine 150 µg
//Magnesium 400 mg
//Zinc 15 mg
//Selenium 70 µg
//Copper 2 mg
//Manganese 2 mg
//Chromium 120 µg
//Molybdenum 75 µg
//Chloride 3,400 mg
class Globals: NSObject {
//MARK: Icomoon helper functions
class func GetMoonIcon(index:Int)->MoonIcons
{
return MoonIcons.allValues[index]
}
class func IndexOfMoonIcon(icon:MoonIcons)->Int
{
if let index:Int = find(MoonIcons.allValues,icon)
{
return index
}
else
{
return -1
}
}
class func GetUIImageFromIcoMoon(icon:MoonIcons, size:CGSize, highlight:Bool)->UIImage
{
// Create a context to render into.
UIGraphicsBeginImageContext(size)
// Work out where the origin of the drawn string should be to get it in
// the centre of the image.
let textOrigin:CGPoint = CGPointMake(5, 5)
let tmpString:NSString = NSString(string: icon.rawValue)
// Draw the string into out image!
let style:NSMutableParagraphStyle = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.Center
if !highlight
{
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: size.height-10)!,
NSForegroundColorAttributeName : ControlBcgSolidColor,
NSParagraphStyleAttributeName : style
]
tmpString.drawAtPoint(textOrigin, withAttributes: textFontAttributes)
}
else
{
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: size.height-10)!,
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSParagraphStyleAttributeName : style
]
tmpString.drawAtPoint(textOrigin, withAttributes: textFontAttributes)
}
let retImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return retImage
}
class func GetAttributedTextForIcon(iconAlignment:NSTextAlignment,iconSize:CGFloat,iconColor:UIColor,icon:String)->NSAttributedString
{
//Prepare Navigation Controller Item
let style:NSMutableParagraphStyle = NSMutableParagraphStyle()
style.alignment = iconAlignment
let textFontAttributes: [String: AnyObject] = [
NSFontAttributeName : UIFont(name: "icomoon", size: iconSize)!,
NSForegroundColorAttributeName : iconColor,
NSParagraphStyleAttributeName : style
]
return NSAttributedString(string: icon , attributes: textFontAttributes)
}
//MARK: Storyboard helper
class func getViewController(identifier:String!)->UIViewController?
{
// get your storyboard
let storyboard = UIStoryboard(name: "Main", bundle: nil)
return storyboard.instantiateViewControllerWithIdentifier(identifier) as? UIViewController
}
//MARK: BMI
class func BMI(gender:Bool, height:Float, weight:Float, age:Int)->Float
{
//BMI = weight(kg)/height2(m2) (Metric Units)
var inMeters = height / 100
return weight/(inMeters*inMeters)
}
class func WeightForBMI(gender:Bool, height:Float, BMI:Float, age:Int)->Float
{
//BMI = weight(kg)/height2(m2) (Metric Units)
var inMeters = height / 100
return BMI * (inMeters*inMeters)
}
}
|
gpl-2.0
|
fe41d9cfb74ba4e91bbbd093aa1e2c46
| 24.020358 | 137 | 0.51546 | 3.195424 | false | false | false | false |
gkaimakas/Ion
|
Pod/Classes/forms/Form.swift
|
1
|
3681
|
//
// Form.swift
// Pods
//
// Created by George Kaimakas on 11/18/15.
//
//
open class Form {
open let id: Int64
open let name: String
fileprivate var dirty = false
fileprivate var submitted = false
fileprivate var currentState = false
fileprivate var previousState = false
fileprivate var sections = [Section]()
fileprivate var formListeners = [FormListener]()
//MARK: - Computed Properties
open var data: [String: Any]{
return sections.map{
$0.data
}.reduce([String:Any]()) { (result:[String: Any], data:[String : Any]) -> [String:Any] in
var _result = result
for (key, value) in data{
_result[key] = value
}
return _result
}
}
open var errors:[String]? {
let errorList = sections.map{
$0.errors
}.filter(){
$0 != nil
}.reduce([String]()) { (result:[String], data: [String]?) -> [String] in
var _result = result
if let _data = data {
_result.append(contentsOf: _data)
}
return _result
}
if errorList.count != 0{
return errorList
}
return nil
}
open var isDirty: Bool{
return dirty
}
open var isSubmitted: Bool{
return submitted
}
open var isValid:Bool {
return validate()
}
open var numberOfSections:Int {
return sections.count
}
//MARK: - Initializers
public init(name:String){
self.id = Int64(Date().timeIntervalSince1970 * 1000)
self.name = name
}
open func addSection(_ section: Section) -> Form{
sections.append(section)
section.addSectionListener(self)
return self
}
open func addFormListener(_ listener: FormListener){
formListeners.append(listener)
}
open func sectionAtIndex(_ index: Int) -> Section{
return sections[index]
}
open func dataAs<T: DictionaryInitProtocol>(_ type: T.Type) -> T? {
return T(dictionary: self.data)
}
//MARK: - Notifications
open func notifyIfFormInputValueChange(_ section: Section, input:Input){
for listener: FormListener in formListeners{
listener.formIputDidChangeValue(self,section: section, input: input)
}
}
open func notifyIfFormStateChange(){
for listener: FormListener in formListeners{
listener.formDidChangeState(self)
}
}
open func notifyIfFormSubmitted(){
for listener: FormListener in formListeners{
listener.formWasSubmitted(self)
}
}
open func setCurrentState(_ state:Bool){
previousState = currentState
currentState = state
}
open func submit(){
for section: Section in sections{
section.submit()
}
submitted = true
notifyIfFormSubmitted()
}
open func validate() -> Bool {
return sections.reduce(true){
$0 && $1.validate()
}
}
}
//MARK: - SectionListener Implementation
extension Form: SectionListener {
public func sectionInputDidChangeValue(_ section: Section, input: Input) {
dirty = true
notifyIfFormInputValueChange(section, input: input)
}
public func sectionDidChangeState(_ section: Section) {
setCurrentState(validate())
}
public func sectionWasSubmitted(_ section: Section) {
}
}
|
mit
|
4b3e9e953567a3bdac447cadf9d23ffa
| 22.902597 | 101 | 0.556642 | 4.695153 | false | false | false | false |
AntonTheDev/CoreFlightAnimation
|
CoreFlightAnimation/CoreFlightAnimationDemo/CoreFlightAnimationDemo/HGAlignment.swift
|
1
|
7096
|
//
// HGAlignment.swift
// Sneakify
//
// Created by Anton Doudarev on 12/8/15.
// Copyright © 2015 Anton Doudarev. All rights reserved.
//
import Foundation
import UIKit
func CGCSRectGetTopLeft(rect : CGRect) -> CGPoint {
return CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect))
}
func CGCSRectGetBottomLeft(rect : CGRect) -> CGPoint {
return CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect))
}
func CGCSRectGetTopRight(rect : CGRect) -> CGPoint {
return CGPointMake(CGRectGetMaxX(rect), CGRectGetMinY(rect))
}
func CGCSRectGetBottomRight(rect : CGRect) -> CGPoint {
return CGPointMake(CGRectGetMaxX(rect), CGRectGetMaxY(rect))
}
func CGCSRectEdgeInset(inputFrame : CGRect, edgeInsets : UIEdgeInsets) -> CGRect {
var retval :CGRect = CGRectMake(inputFrame.origin.x + edgeInsets.left, inputFrame.origin.y + edgeInsets.top, 0, 0)
retval.size.width = CGRectGetWidth(inputFrame) - (edgeInsets.left + edgeInsets.right)
retval.size.height = CGRectGetHeight(inputFrame) - (edgeInsets.top + edgeInsets.bottom)
return retval
}
func CGCSRectEdgeOutset(inputFrame : CGRect, edgeInsets : UIEdgeInsets) -> CGRect {
let invertedEdgeInsets : UIEdgeInsets = UIEdgeInsetsMake(-edgeInsets.top, -edgeInsets.left, -edgeInsets.bottom, -edgeInsets.right)
return CGCSRectEdgeInset(inputFrame, edgeInsets: invertedEdgeInsets)
}
func CGCSRectCenterInRect(sourceRect : CGRect, destRect : CGRect) -> CGRect {
var newRect : CGRect = sourceRect
newRect.origin.x = destRect.origin.x + (destRect.size.width - sourceRect.size.width) / 2.0
newRect.origin.y = destRect.origin.y + (destRect.size.height - sourceRect.size.height) / 2.0
return newRect
}
func CGCSPointVerticalCenterBetweenRect(topRect : CGRect, bottomRect : CGRect) -> CGPoint {
let topCenter : CGPoint = CGCSRectGetCenter(topRect)
let topBottomY = CGRectGetMaxY(topRect)
let bottomTopY = CGRectGetMinY(bottomRect)
return CGPointMake(topCenter.x, topBottomY + (bottomTopY - topBottomY) / 2.0)
}
func CGCSRectAspectFitRatio(inRect : CGRect, maxRect : CGRect) -> CGFloat {
if (CGRectGetWidth(inRect) == 0 || CGRectGetHeight(inRect) == 0) {
return 1.0
}
let horizontalRatio = CGRectGetWidth(maxRect) / CGRectGetWidth(inRect)
let verticalRatio = CGRectGetHeight(maxRect) / CGRectGetHeight(inRect)
return (horizontalRatio < verticalRatio ? horizontalRatio : verticalRatio)
}
func CGCSRectAspectFit(inRect : CGRect, maxRect : CGRect) -> CGRect {
let ratio = CGCSRectAspectFitRatio(inRect, maxRect: maxRect)
let newSize = CGSizeMake(CGRectGetWidth(inRect) * ratio, CGRectGetHeight(inRect) * ratio)
return CGRectMake((CGRectGetWidth(maxRect) - newSize.width) / 2.0 + maxRect.origin.x,
(CGRectGetHeight(maxRect) - newSize.height) / 2.0 + maxRect.origin.y,
newSize.width,
newSize.height)
}
func CGCSRectAspectFillRatio(inRect : CGRect, maxRect : CGRect) -> CGFloat {
if CGRectGetWidth(inRect) == 0 || CGRectGetHeight(inRect) == 0 {
return 1.0
}
let horizontalRatio = CGRectGetWidth(maxRect) / CGRectGetWidth(inRect)
let verticalRatio = CGRectGetHeight(maxRect) / CGRectGetHeight(inRect)
return (horizontalRatio < verticalRatio ? verticalRatio : horizontalRatio)
}
func CGCSRectAspectFill(inRect : CGRect, maxRect : CGRect) -> CGRect {
let ratio = CGCSRectAspectFillRatio(inRect, maxRect: maxRect)
let newSize = CGSizeMake(CGRectGetWidth(inRect) * ratio, CGRectGetHeight(inRect) * ratio)
return CGRectMake((CGRectGetWidth(maxRect) - newSize.width) / 2.0 + maxRect.origin.x,
(CGRectGetHeight(maxRect) - newSize.height) / 2.0 + maxRect.origin.y,
newSize.width,
newSize.height)
}
func CGCSRectGetCenter(inRect : CGRect) -> CGPoint {
return CGPointMake(ceil(inRect.origin.x + inRect.width * 0.5), ceil(inRect.origin.y + inRect.height * 0.5))
}
func alignedHorizontalOriginWithFrame(source : CGRect, dest : CGRect, align : HGHorizontalAlign) -> CGFloat {
var origin = source.origin.x
switch (align) {
case .Left:
origin = dest.origin.x - source.size.width;
case .Right:
origin = CGRectGetMaxX(dest);
case .Center:
origin = dest.origin.x + ((dest.size.width - source.size.width) / 2.0);
case .LeftEdge:
origin = dest.origin.x;
case .RightEdge:
origin = CGRectGetMaxX(dest) - source.size.width;
}
return round(origin)
}
func alignedVerticalOriginWithFrame(source : CGRect, dest : CGRect, align : HGVerticalAlign) -> CGFloat {
var origin = source.origin.x
switch (align) {
case .Top:
origin = dest.origin.y
case .Base:
origin = CGRectGetMaxY(dest) - source.size.height
case .Center:
origin = dest.origin.y + ((dest.size.height - source.size.height) / 2.0)
case .Above:
origin = dest.origin.y - source.size.height
case .Below:
origin = CGRectGetMaxY(dest)
}
return round(origin)
}
enum HGVerticalAlign {
case Top
case Base
case Center
case Above
case Below
}
enum HGHorizontalAlign {
case Left
case Right
case Center
case RightEdge
case LeftEdge
}
extension UIView {
func alignToView(otherView : UIView, horizontal: HGHorizontalAlign, vertical : HGVerticalAlign , horizontalOffset : CGFloat = 0.0, verticalOffset : CGFloat = 0.0) {
self.alignToFrame(otherView.frame, horizontal : horizontal, vertical : vertical, horizontalOffset : horizontalOffset, verticalOffset : verticalOffset)
}
func alignToFrame(otherFrame : CGRect,
horizontal : HGHorizontalAlign,
vertical : HGVerticalAlign,
horizontalOffset : CGFloat = 0.0,
verticalOffset : CGFloat = 0.0) {
let x = alignedHorizontalOriginWithFrame(self.frame, dest:otherFrame, align : horizontal)
let y = alignedVerticalOriginWithFrame(self.frame, dest:otherFrame, align : vertical)
self.frame = CGRectIntegral(CGRectMake(x + horizontalOffset, y + verticalOffset, self.frame.size.width, self.frame.size.height))
}
func alignWithSize(newSize : CGSize,
toFrame : CGRect,
horizontal : HGHorizontalAlign,
vertical : HGVerticalAlign,
horizontalOffset : CGFloat = 0.0,
verticalOffset : CGFloat = 0.0) {
var newRect = CGRectMake(0,0, newSize.width, newSize.height)
newRect.origin.x = alignedHorizontalOriginWithFrame(newRect, dest:toFrame, align : horizontal) + horizontalOffset
newRect.origin.y = alignedVerticalOriginWithFrame(newRect, dest:toFrame, align : vertical) + verticalOffset
if CGRectEqualToRect(self.frame, CGRectIntegral(newRect)) == false {
self.frame = newRect
}
}
}
|
mit
|
5f21c34a07badbac458e6c9346b7afab
| 37.351351 | 169 | 0.66864 | 4.151551 | false | false | false | false |
Jvaeyhcd/NavTabBarController
|
NavTabBarController/SlippedSegmentView.swift
|
1
|
23464
|
//
// NavTabBar.swift
// govlan
//
// Created by polesapp-hcd on 2016/11/2.
// Copyright © 2016年 Polesapp. All rights reserved.
//
import UIKit
protocol HcdTabBarDelegate {
func tabBar(tabBar: SlippedSegmentView, willSelectItemAtIndex: Int) -> Bool
func tabBar(tabBar: SlippedSegmentView, didSelectedItemAtIndex: Int)
func leftButtonClicked()
func rightButtonClicked()
}
extension HcdTabBarDelegate {
// 定义可选协议
func leftButtonClicked() {
}
func rightButtonClicked() {
}
}
class SlippedSegmentView: UIView, UIScrollViewDelegate {
var delegate: HcdTabBarDelegate?
var leftAndRightSpacing = CGFloat(0)
// 选中Item背景的Insets
private var itemSelectedBgInsets = UIEdgeInsetsMake(40, 15, 0, 15)
// 水平内边距
private var itemHorizontalPadding = CGFloat(15)
// Item的宽度,默认值70
private var itemWidth = CGFloat(70)
// 是否根据Item文字自适应Item的宽度,默认false
private var autoResizeItemWidth = false
// item的文字数组
private var titles: [String]!
// 选中的Item的index
private var selectedItemIndex = -1
private var scrollView: UIScrollView?
private var items: [SlippedSegmentItem] = [SlippedSegmentItem]()
private var itemSelectedBgImageView: UIImageView?
private var itemSelectedBgImageViewColor: UIColor = UIColor.red
// item的选中字体大小,默认20
private var itemTitleSelectedFont = UIFont.systemFont(ofSize: 20)
// item的没有选中字体大小,默认16
private var itemTitleFont = UIFont.systemFont(ofSize: 16)
// 拖动内容视图时,item的颜色是否根据拖动位置显示渐变效果,默认为false
private var itemColorChangeFollowContentScroll = true
// 拖动内容视图时,item的字体是否根据拖动位置显示渐变效果,默认为false
private var itemFontChangeFollowContentScroll = true
// TabItem的选中背景是否随contentView滑动而移动
private var itemSelectedBgScrollFollowContent = true
// TabItem选中切换时,是否显示动画
private var itemSelectedBgSwitchAnimated = true
// Item未选中的字体颜色
private var itemTitleColor: UIColor = UIColor.lightGray
// Item选中的字体颜色
private var itemTitleSelectedColor: UIColor = UIColor.init(red: 0.000, green: 0.655, blue: 0.937, alpha: 1.00)//[UIColor colorWithRed:0.000 green:0.655 blue:0.937 alpha:1.00]
// 左右两边的图片按钮
private var leftButton, rightButton: UIButton?
// 左右按钮是否显示
private var showLeftButton = false, showRightButton = false
private var buttonWidth = CGFloat(50)
private var paddingTop = CGFloat(0), paddingLeft = CGFloat(0), paddingBottom = CGFloat(0), paddingRight = CGFloat(0)
override init(frame: CGRect) {
super.init(frame: frame)
initSubViews()
initDatas()
}
// MARK: - Setter
/**
设置切换是否动态改变Item字体颜色
- parameter itemColorChangeFollowContentScroll: Bool true or false
*/
func setItemColorChangeFollowContentScroll(itemColorChangeFollowContentScroll: Bool) {
self.itemColorChangeFollowContentScroll = itemColorChangeFollowContentScroll
}
/**
设置切换是否动态改变Item字体大小
- parameter itemFontChangeFollowContentScroll: Bool true or false
*/
func setItemFontChangeFollowContentScroll(itemFontChangeFollowContentScroll: Bool) {
self.itemFontChangeFollowContentScroll = itemFontChangeFollowContentScroll
}
func setItemTitleFont(itemTitleFont: UIFont) {
self.itemTitleFont = itemTitleFont
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setItemTitleSelectedFont(itemTitleSelectedFont: UIFont) {
self.itemTitleSelectedFont = itemTitleSelectedFont
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setItemTitleColor(itemTitleColor: UIColor) {
self.itemTitleColor = itemTitleColor
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setItemTitleSelectedColor(itemTitleSelectedColor: UIColor) {
self.itemTitleSelectedColor = itemTitleSelectedColor
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setItemWidth(itemWidth: CGFloat) {
self.itemWidth = itemWidth
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setItemHorizontalPadding(itemHorizontalPadding: CGFloat) {
self.itemHorizontalPadding = itemHorizontalPadding
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setAutoResizeItemWidth(auto: Bool) {
self.autoResizeItemWidth = auto
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setFramePadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {
self.paddingTop = top
self.paddingLeft = left
self.paddingBottom = bottom
self.paddingRight = right
updateScrollViewFrame()
}
func setItemSelectedBgImageViewColor(itemSelectedBgImageViewColor: UIColor) {
self.itemSelectedBgImageViewColor = itemSelectedBgImageViewColor
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
/**
设置选中Item下标
- parameter selectedItemIndex: 选中Item的index
*/
func setSelectedItemIndex(selectedItemIndex: Int) {
if self.items.count == 0 || selectedItemIndex < 0 || selectedItemIndex >= self.items.count {
return
}
//
// if self.selectedItemIndex >= self.items.count || self.selectedItemIndex < 0 {
// return
// }
if self.selectedItemIndex >= 0 && self.selectedItemIndex < self.items.count {
let oldSelectedItem = self.items[self.selectedItemIndex]
oldSelectedItem.isSelected = false
if self.itemFontChangeFollowContentScroll {
// 如果支持字体平滑渐变切换,则设置item的scale
let itemTitleUnselectedFontScale = self.itemTitleFont.pointSize / self.itemTitleSelectedFont.pointSize
oldSelectedItem.transform = CGAffineTransform(scaleX: itemTitleUnselectedFontScale, y: itemTitleUnselectedFontScale)
} else {
// 如果支持字体平滑渐变切换,则直接设置字体
oldSelectedItem.setTitleFont(titleFont: self.itemTitleFont)
}
}
let newSelectedItem = self.items[selectedItemIndex]
newSelectedItem.isSelected = true
if self.itemFontChangeFollowContentScroll {
// 如果支持字体平滑渐变切换,则设置item的scale
newSelectedItem.transform = CGAffineTransform(scaleX: 1, y: 1)
} else {
// 如果支持字体平滑渐变切换,则直接设置字体
newSelectedItem.setTitleFont(titleFont: self.itemTitleSelectedFont)
}
if self.itemSelectedBgSwitchAnimated && self.selectedItemIndex >= 0 {
UIView.animate(withDuration: 0.25, animations: {
self.updateSelectedBgFrameWithIndex(index: selectedItemIndex)
})
} else {
self.updateSelectedBgFrameWithIndex(index: selectedItemIndex)
}
// didSelectedItemAtIndex
if nil != self.delegate {
self.delegate?.tabBar(tabBar: self, didSelectedItemAtIndex: selectedItemIndex)
}
self.selectedItemIndex = selectedItemIndex
setSelectedItemCenter()
}
/**
设置Items
- parameter items: Items数组
*/
func setItems(items: [SlippedSegmentItem]) {
self.items.forEach{ $0.removeFromSuperview() }
self.items = items
updateItemsFrame()
setSelectedItemIndex(selectedItemIndex: self.selectedItemIndex)
updateItemsScaleIfNeeded()
}
func setItemSelectedBgInsets(itemSelectedBgInsets: UIEdgeInsets) {
self.itemSelectedBgInsets = itemSelectedBgInsets
updateSelectedBgFrameWithIndex(index: self.selectedItemIndex)
}
/**
Item点击事件
- parameter item: 被点击的Item
*/
@objc private func tabItemClicked(item: SlippedSegmentItem) {
if self.selectedItemIndex == item.index {
return
}
setSelectedItemIndex(selectedItemIndex: item.index)
}
/**
左边按钮点击事件
- parameter button: 点击的Button
*/
@objc private func leftButtonClicked(button: UIButton) {
if nil != self.delegate {
self.delegate?.leftButtonClicked()
}
}
/**
右边按钮点击事件
- parameter button: 点击的Button
*/
@objc private func rightButtonClicked(button: UIButton) {
if nil != self.delegate {
self.delegate?.rightButtonClicked()
}
}
// MARK: - public fucntion
func updateFrame(frame: CGRect) {
self.frame = frame
updateScrollViewFrame()
}
/**
设置是否显示选中Item的背景图片
- parameter show: ture or false
*/
func showSelectedBgView(show: Bool) {
self.itemSelectedBgScrollFollowContent = show
self.itemSelectedBgImageView?.isHidden = !show
}
/**
设置Items的titles
- parameter titles: title数组
*/
func setTitles(titles: [String]) {
self.titles = titles
var items = [SlippedSegmentItem]()
for title in titles {
let item = SlippedSegmentItem()
item.setTitle(title, for: .normal)
items.append(item)
}
setItems(items: items)
}
/**
显示左边按钮
- parameter image: 按钮图片
*/
func showLeftBarButton(withImage image: UIImage) {
self.showLeftButton = true
if nil == self.leftButton {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
self.leftButton = UIButton.init(frame: CGRect(x: 0, y: statusBarHeight, width: buttonWidth, height: self.bounds.height - statusBarHeight))
self.leftButton?.backgroundColor = UIColor.clear
self.leftButton?.addTarget(self, action: #selector(leftButtonClicked(button:)), for: .touchUpInside)
self.addSubview(self.leftButton!)
}
self.leftButton?.setImage(image, for: .normal)
self.updateScrollViewFrame()
}
/**
显示右边按钮
- parameter image: 按钮图片
*/
func showRightBarButton(withImage image: UIImage) {
self.showRightButton = true
if nil == self.rightButton {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
self.rightButton = UIButton.init(frame: CGRect(x: self.bounds.width - buttonWidth, y: statusBarHeight, width: buttonWidth, height: self.bounds.height - statusBarHeight))
self.rightButton?.backgroundColor = UIColor.clear
self.rightButton?.addTarget(self, action: #selector(rightButtonClicked(button:)), for: .touchUpInside)
self.addSubview(self.rightButton!)
}
self.rightButton?.setImage(image, for: .normal)
self.updateScrollViewFrame()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - private function
/**
初始化一些界面组件
- returns:
*/
private func initSubViews() {
if nil == self.scrollView {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
self.scrollView = UIScrollView.init(frame: CGRect(x: 0, y: statusBarHeight, width: self.bounds.width, height: self.bounds.height - statusBarHeight))
self.scrollView?.showsVerticalScrollIndicator = false
self.scrollView?.showsHorizontalScrollIndicator = false
self.addSubview(self.scrollView!)
}
if nil == self.itemSelectedBgImageView {
self.itemSelectedBgImageView = UIImageView.init(frame: .zero)
self.itemSelectedBgImageView?.backgroundColor = itemSelectedBgImageViewColor
}
}
private func initDatas() {
self.titles = [String]()
}
/**
更新items的Frame
*/
private func updateItemsFrame() {
if self.items.count == 0 {
return
}
// 将item从superview上删除
self.items.forEach{ $0.removeFromSuperview() }
self.itemSelectedBgImageView!.removeFromSuperview()
if nil != self.scrollView {
self.itemSelectedBgImageView?.backgroundColor = itemSelectedBgImageViewColor
self.scrollView?.addSubview(self.itemSelectedBgImageView!)
var x = self.leftAndRightSpacing
var index = 0
for item in self.items {
var width = CGFloat(0)
if autoResizeItemWidth {
let title = titles[index] as NSString
let size = title.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 20), options: .usesFontLeading, attributes: [NSFontAttributeName: self.itemTitleFont], context: nil)
width = size.width + itemHorizontalPadding + itemHorizontalPadding
} else if itemWidth > 0 {
width = itemWidth
}
item.frame = CGRect(x: x, y: 0, width: width, height: self.scrollView!.bounds.height)
item.setTitleColor(titleColor: self.itemTitleColor)
item.setTitleSelectedColor(titleSelectedColor: self.itemTitleSelectedColor)
item.setTitleFont(titleFont: self.itemTitleFont)
item.addTarget(self, action: #selector(tabItemClicked(item:)), for: .touchUpInside)
item.index = index
x = x + width
index = index + 1
self.scrollView?.addSubview(item)
}
self.scrollView?.contentSize = CGSize(width: MAX(value1: x + self.leftAndRightSpacing, value2: self.scrollView!.frame.size.width), height: self.scrollView!.frame.size.height)
}
}
/**
更新ScrollView的Frame
*/
private func updateScrollViewFrame() {
var x = self.paddingLeft
let y = self.paddingTop
var width = self.frame.size.width - self.paddingLeft - self.paddingRight
let height = self.frame.size.height - self.paddingTop - self.paddingBottom
if self.showLeftButton {
x = self.buttonWidth
width = width - self.buttonWidth
}
if self.showRightButton {
width = width - self.buttonWidth
}
self.scrollView?.frame = CGRect(x: x, y: y, width: width, height: height)
self.updateItemsFrame()
}
/**
更新选中的Item的背景
- parameter index: 选中的Item的index
*/
private func updateSelectedBgFrameWithIndex(index: Int) {
if index < 0 || index > self.items.count {
return
}
let item = self.items[index]
let width = item.frame.size.width - self.itemSelectedBgInsets.left - self.itemSelectedBgInsets.right
let height = item.frame.size.height - self.itemSelectedBgInsets.top - self.itemSelectedBgInsets.bottom
self.itemSelectedBgImageView!.frame = CGRect(x: item.frame.origin.x + self.itemSelectedBgInsets.left,
y: item.frame.origin.y + self.itemSelectedBgInsets.top,
width: width,
height: height)
}
/**
更新item的大小缩放
*/
private func updateItemsScaleIfNeeded() {
if self.itemFontChangeFollowContentScroll {
self.items.forEach{
$0.setTitleFont(titleFont: self.itemTitleSelectedFont)
if !$0.isSelected {
let itemTitleUnselectedFontScale = self.itemTitleFont.pointSize / self.itemTitleSelectedFont.pointSize
$0.transform = CGAffineTransform(scaleX: itemTitleUnselectedFontScale, y: itemTitleUnselectedFontScale)
}
}
}
}
/**
获取选中的Item
- returns: 选中的Item
*/
private func selectedItem() -> SlippedSegmentItem? {
if self.selectedItemIndex >= 0 && self.selectedItemIndex < self.items.count {
return self.items[self.selectedItemIndex]
}
return nil
}
/**
将选中的Item更新到中间位置
*/
private func setSelectedItemCenter() {
let selectedItem = self.selectedItem()
if nil == selectedItem {
return
}
// 修改偏移量
var offsetX = selectedItem!.center.x - self.scrollView!.frame.size.width * 0.5
// 处理最小滚动偏移量
if offsetX < 0 {
offsetX = 0
}
// 处理最大滚动偏移量
let maxOffsetX = self.scrollView!.contentSize.width - self.scrollView!.frame.size.width
if offsetX > maxOffsetX {
offsetX = maxOffsetX
}
self.scrollView?.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
func MAX(value1: CGFloat, value2: CGFloat) -> CGFloat {
if value1 > value2 {
return value1
}
return value2
}
//MARK: - UIScrollViewDelegate
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// 这里的Delegate是给NavTabController调用的
if scrollView.isEqual(self.scrollView) {
return
}
let page = Int(scrollView.contentOffset.x) / Int(scrollView.frame.size.width)
setSelectedItemIndex(selectedItemIndex: page)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 这里的Delegate是给NavTabController调用的
if scrollView.isEqual(self.scrollView) {
return
}
// 如果不是手势拖动导致的此方法被调用,不处理
if !(scrollView.isDragging || scrollView.isDecelerating) {
return
}
// 滑动越界不处理
let offsetX = scrollView.contentOffset.x
let scrollViewWidth = scrollView.frame.size.width
if offsetX < 0 {
return
}
if offsetX > scrollView.contentSize.width - scrollViewWidth {
return
}
let leftIndex = Int(offsetX) / Int(scrollViewWidth)
let rightIndex = leftIndex + 1
if leftIndex >= self.items.count || rightIndex >= self.items.count {
return
}
let leftItem = self.items[leftIndex]
let rightItem = self.items[rightIndex]
// 计算右边按钮偏移量
var rightScale = offsetX / scrollViewWidth
// 只想要 0~1
rightScale = rightScale - CGFloat(leftIndex)
let leftScale = 1 - rightScale
if self.itemFontChangeFollowContentScroll {
// 如果支持title大小跟随content的拖动进行变化,并且未选中字体和已选中字体的大小不一致
let itemTitleUnselectedFontScale = self.itemTitleFont.pointSize / self.itemTitleSelectedFont.pointSize
// 计算字体大小的差值
let diff = itemTitleUnselectedFontScale - 1
// 根据偏移量和差值,计算缩放值
leftItem.transform = CGAffineTransform(scaleX: rightScale * diff + 1, y: rightScale * diff + 1)
rightItem.transform = CGAffineTransform(scaleX: leftScale * diff + 1, y: leftScale * diff + 1)
}
// 计算颜色的渐变
if self.itemColorChangeFollowContentScroll {
var normalRed = CGFloat(0), normalGreen = CGFloat(0), normalBlue = CGFloat(0)
var selectedRed = CGFloat(0), selectedGreen = CGFloat(0), selectedBlue = CGFloat(0)
self.itemTitleColor.getRed(&normalRed, green: &normalGreen, blue: &normalBlue, alpha: nil)
self.itemTitleSelectedColor.getRed(&selectedRed, green: &selectedGreen, blue: &selectedBlue, alpha: nil)
// 获取选中和未选中状态的颜色差值
let redDiff = selectedRed - normalRed
let greenDiff = selectedGreen - normalGreen
let blueDiff = selectedBlue - normalBlue
// 根据颜色值的差值和偏移量,设置tabItem的标题颜色
leftItem.titleLabel!.textColor = UIColor.init(red: leftScale * redDiff + normalRed, green: leftScale * greenDiff + normalGreen, blue: leftScale * blueDiff + normalBlue, alpha: 1)
rightItem.titleLabel!.textColor = UIColor.init(red: rightScale * redDiff + normalRed, green: rightScale * greenDiff + normalGreen, blue: rightScale * blueDiff + normalBlue, alpha: 1)
}
// 计算背景的frame
if self.itemSelectedBgScrollFollowContent {
var frame = self.itemSelectedBgImageView!.frame
let xDiff = rightItem.frame.origin.x - leftItem.frame.origin.x
frame.origin.x = rightScale * xDiff + leftItem.frame.origin.x + self.itemSelectedBgInsets.left
let widthDiff = rightItem.frame.size.width - leftItem.frame.size.width
if widthDiff != 0 {
let leftSelectedBgWidth = leftItem.frame.size.width - self.itemSelectedBgInsets.left - self.itemSelectedBgInsets.right
frame.size.width = rightScale * widthDiff + leftSelectedBgWidth
}
self.itemSelectedBgImageView!.frame = frame
}
}
}
|
mit
|
517ab2c3375f2ff2265ce63cd9a6d269
| 33.703588 | 211 | 0.616498 | 4.893313 | false | false | false | false |
PrettySwift/SwiftCatalog
|
SwiftCatalog/SwiftCatalog/View Controller/CatalogTableViewController.swift
|
1
|
1873
|
//
// CatalogTableViewController.swift
// SwiftCatalog
//
// Created by Ben Johnson on 11/12/15.
// Copyright © 2015 Pretty Swift. All rights reserved.
//
import UIKit
class CatalogTableViewController: UITableViewController {
let catalogItems: [CatalogItem] = {
guard let URL = NSBundle.mainBundle().URLForResource("CatalogItems", withExtension: "plist") else { return [] }
return CatalogItemLoader(fileURL: URL).catalogItems
}()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let destinationViewController = segue.destinationViewController as? ItemViewController, indexPathOfSelectedRow = tableView.indexPathForSelectedRow else { return }
destinationViewController.catalogItem = catalogItems[indexPathOfSelectedRow.row]
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return catalogItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CatalogItemCellReuseIdentifier", forIndexPath: indexPath)
cell.textLabel?.text = catalogItems[indexPath.row].title ?? ""
cell.imageView?.image = catalogItems[indexPath.row].image
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("CatalogDetailSegue", sender: tableView.cellForRowAtIndexPath(indexPath))
}
}
|
mit
|
9dd31da9dd7bc92fb187093ab158b1d9
| 35.705882 | 176 | 0.722756 | 5.60479 | false | false | false | false |
ps2/rileylink_ios
|
MinimedKitUI/Setup/MinimedPumpIDSetupViewController.swift
|
1
|
15666
|
//
// MinimedPumpIDSetupViewController.swift
// Loop
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import UIKit
import LoopKit
import LoopKitUI
import MinimedKit
import RileyLinkKit
class MinimedPumpIDSetupViewController: SetupTableViewController {
var rileyLinkPumpManager: RileyLinkPumpManager!
private enum RegionCode: String {
case northAmerica = "NA"
case canada = "CA/CM"
case worldWide = "WW"
var region: PumpRegion {
switch self {
case .northAmerica:
return .northAmerica
case .canada:
return .canada
case .worldWide:
return .worldWide
}
}
}
private var pumpRegionCode: RegionCode? {
didSet {
regionAndColorPickerCell.regionLabel.text = pumpRegionCode?.region.description
regionAndColorPickerCell.regionLabel.textColor = nil
updateStateForSettings()
}
}
private var pumpColor: PumpColor? {
didSet {
regionAndColorPickerCell.pumpImageView.image = .pumpImage(in: pumpColor, isLargerModel: true, isSmallImage: true)
updateStateForSettings()
}
}
private var pumpID: String? {
get {
return pumpIDTextField.text
}
set {
pumpIDTextField.text = newValue
}
}
private var pumpOps: PumpOps?
private var pumpState: PumpState?
private var pumpFirmwareVersion: String?
var maxBasalRateUnitsPerHour: Double!
var maxBolusUnits: Double!
var basalSchedule: BasalRateSchedule!
private var isSentrySetUpNeeded: Bool = false
var pumpManagerState: MinimedPumpManagerState? {
get {
guard
let navVC = navigationController as? MinimedPumpManagerSetupViewController,
let insulinType = navVC.insulinType,
let pumpColor = pumpColor,
let pumpID = pumpID,
let pumpModel = pumpState?.pumpModel,
let pumpRegion = pumpRegionCode?.region,
let timeZone = pumpState?.timeZone,
let pumpFirmwareVersion = pumpFirmwareVersion
else {
return nil
}
return MinimedPumpManagerState(
isOnboarded: false,
useMySentry: pumpState?.useMySentry ?? true,
pumpColor: pumpColor,
pumpID: pumpID,
pumpModel: pumpModel,
pumpFirmwareVersion: pumpFirmwareVersion,
pumpRegion: pumpRegion,
rileyLinkConnectionState: rileyLinkPumpManager.rileyLinkConnectionManagerState,
timeZone: timeZone,
suspendState: .resumed(Date()),
insulinType: insulinType,
lastTuned: pumpState?.lastTuned,
lastValidFrequency: pumpState?.lastValidFrequency
)
}
}
var pumpManager: MinimedPumpManager? {
guard let pumpManagerState = pumpManagerState else {
return nil
}
return MinimedPumpManager(
state: pumpManagerState,
rileyLinkDeviceProvider: rileyLinkPumpManager.rileyLinkDeviceProvider)
}
// MARK: -
@IBOutlet weak var pumpIDTextField: UITextField!
@IBOutlet fileprivate weak var regionAndColorPickerCell: RegionAndColorPickerTableViewCell!
@IBOutlet weak var activityIndicator: SetupIndicatorView!
@IBOutlet weak var loadingLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
regionAndColorPickerCell.pickerView.delegate = self
regionAndColorPickerCell.pickerView.dataSource = self
continueState = .inputSettings
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: UIResponder.keyboardDidHideNotification, object: nil)
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard continueState != .reading else {
return
}
if let cell = tableView.cellForRow(at: indexPath) as? RegionAndColorPickerTableViewCell {
cell.becomeFirstResponder()
// Apply initial values to match the picker
if pumpRegionCode == nil {
pumpRegionCode = MinimedPumpIDSetupViewController.regionRows[0]
}
if pumpColor == nil {
pumpColor = MinimedPumpIDSetupViewController.colorRows[0]
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - Navigation
private enum State {
case loadingView
case inputSettings
case readyToRead
case reading
case completed
}
private var continueState: State = .loadingView {
didSet {
switch continueState {
case .loadingView:
updateStateForSettings()
case .inputSettings:
pumpIDTextField.isEnabled = true
activityIndicator.state = .hidden
footerView.primaryButton.isEnabled = false
footerView.primaryButton.setConnectTitle()
lastError = nil
case .readyToRead:
pumpIDTextField.isEnabled = true
activityIndicator.state = .hidden
footerView.primaryButton.isEnabled = true
footerView.primaryButton.setConnectTitle()
case .reading:
pumpIDTextField.isEnabled = false
activityIndicator.state = .indeterminantProgress
footerView.primaryButton.isEnabled = false
footerView.primaryButton.setConnectTitle()
lastError = nil
case .completed:
pumpIDTextField.isEnabled = true
activityIndicator.state = .completed
footerView.primaryButton.isEnabled = true
footerView.primaryButton.resetTitle()
lastError = nil
}
}
}
private var lastError: Error? {
didSet {
guard oldValue != nil || lastError != nil else {
return
}
var errorText = lastError?.localizedDescription
if let error = lastError as? LocalizedError {
let localizedText = [error.errorDescription, error.failureReason, error.recoverySuggestion].compactMap({ $0 }).joined(separator: ". ")
if !localizedText.isEmpty {
errorText = localizedText
}
}
tableView.beginUpdates()
loadingLabel.text = errorText
let isHidden = (errorText == nil)
loadingLabel.isHidden = isHidden
tableView.endUpdates()
// If we changed the error text, update the continue state
if !isHidden {
updateStateForSettings()
}
}
}
private func updateStateForSettings() {
let isReadyToRead = pumpRegionCode != nil && pumpColor != nil && pumpID?.count == 6
if isReadyToRead {
continueState = .readyToRead
} else {
continueState = .inputSettings
}
}
private func setupPump(with settings: PumpSettings) {
continueState = .reading
let pumpOps = MinimedPumpOps(pumpSettings: settings, pumpState: pumpState, delegate: self)
self.pumpOps = pumpOps
pumpOps.runSession(withName: "Pump ID Setup", usingSelector: rileyLinkPumpManager.rileyLinkDeviceProvider.firstConnectedDevice, { (session) in
guard let session = session else {
DispatchQueue.main.async {
self.lastError = PumpManagerError.connection(MinimedPumpManagerError.noRileyLink)
}
return
}
do {
_ = try session.tuneRadio()
let model = try session.getPumpModel()
var isSentrySetUpNeeded = false
self.pumpFirmwareVersion = try session.getPumpFirmwareVersion()
// Radio
if model.hasMySentry {
let isSentryEnabled = try session.getOtherDevicesEnabled()
if isSentryEnabled {
let sentryIDCount = try session.getOtherDevicesIDs().ids.count
isSentrySetUpNeeded = (sentryIDCount == 0)
} else {
isSentrySetUpNeeded = true
}
} else {
// Pre-sentry models need a remote ID to decrease the radio wake interval
let remoteIDCount = try session.getRemoteControlIDs().ids.count
if remoteIDCount == 0 {
try session.setRemoteControlID(Data([9, 9, 9, 9, 9, 9]), atIndex: 2)
}
try session.setRemoteControlEnabled(true)
}
// Settings
let newSchedule = BasalSchedule(repeatingScheduleValues: self.basalSchedule.items)
try session.setBasalSchedule(newSchedule, for: .standard)
try session.setMaxBolus(units: self.maxBolusUnits)
try session.setMaxBasalRate(unitsPerHour: self.maxBasalRateUnitsPerHour)
try session.selectBasalProfile(.standard)
try session.setTimeToNow(in: .current)
DispatchQueue.main.async {
self.isSentrySetUpNeeded = isSentrySetUpNeeded
if self.pumpState != nil {
self.continueState = .completed
} else {
self.lastError = PumpManagerError.connection(MinimedPumpManagerError.noRileyLink)
}
}
} catch let error {
DispatchQueue.main.async {
self.lastError = error
}
}
})
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
return continueState == .completed
}
override func continueButtonPressed(_ sender: Any) {
if case .completed = continueState {
if let setupViewController = navigationController as? MinimedPumpManagerSetupViewController,
let pumpManager = pumpManager // create mdt 1
{
setupViewController.pumpManagerSetupComplete(pumpManager)
}
if isSentrySetUpNeeded {
performSegue(withIdentifier: "Sentry", sender: sender)
} else {
super.continueButtonPressed(sender)
}
} else if case .readyToRead = continueState, let pumpID = pumpID, let pumpRegion = pumpRegionCode?.region {
#if targetEnvironment(simulator)
self.continueState = .completed
self.pumpState = PumpState(timeZone: .currentFixed, pumpModel: PumpModel(rawValue:
"523")!, useMySentry: false)
self.pumpFirmwareVersion = "2.4Mock"
#else
setupPump(with: PumpSettings(pumpID: pumpID, pumpRegion: pumpRegion))
#endif
}
}
override func cancelButtonPressed(_ sender: Any) {
if regionAndColorPickerCell.isFirstResponder {
regionAndColorPickerCell.resignFirstResponder()
} else if pumpIDTextField.isFirstResponder {
pumpIDTextField.resignFirstResponder()
} else {
super.cancelButtonPressed(sender)
}
}
@objc func keyboardDidHide() {
regionAndColorPickerCell.resignFirstResponder()
}
}
extension MinimedPumpIDSetupViewController: UIPickerViewDelegate, UIPickerViewDataSource {
private static let regionRows: [RegionCode] = [.northAmerica, .canada, .worldWide]
private static let colorRows: [PumpColor] = [.blue, .clear, .purple, .smoke, .pink]
private enum PickerViewComponent: Int {
case region
case color
static let count = 2
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch PickerViewComponent(rawValue: component)! {
case .region:
return MinimedPumpIDSetupViewController.regionRows[row].rawValue
case .color:
return MinimedPumpIDSetupViewController.colorRows[row].rawValue
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch PickerViewComponent(rawValue: component)! {
case .region:
pumpRegionCode = MinimedPumpIDSetupViewController.regionRows[row]
case .color:
pumpColor = MinimedPumpIDSetupViewController.colorRows[row]
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return PickerViewComponent.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch PickerViewComponent(rawValue: component)! {
case .region:
return MinimedPumpIDSetupViewController.regionRows.count
case .color:
return MinimedPumpIDSetupViewController.colorRows.count
}
}
}
extension MinimedPumpIDSetupViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text, let stringRange = Range(range, in: text) else {
updateStateForSettings()
return true
}
let newText = text.replacingCharacters(in: stringRange, with: string)
if newText.count >= 6 {
if newText.count == 6 {
textField.text = newText
textField.resignFirstResponder()
}
updateStateForSettings()
return false
}
textField.text = newText
updateStateForSettings()
return false
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension MinimedPumpIDSetupViewController: PumpOpsDelegate {
// TODO: create PumpManager and report it to Loop before pump setup
// No pumpManager available yet, so no device logs.
func willSend(_ message: String) {}
func didReceive(_ message: String) {}
func didError(_ message: String) {}
func pumpOps(_ pumpOps: PumpOps, didChange state: PumpState) {
DispatchQueue.main.async {
self.pumpState = state
}
}
}
class RegionAndColorPickerTableViewCell: UITableViewCell {
override var canBecomeFirstResponder: Bool {
return true
}
fileprivate private(set) lazy var pickerView = UIPickerView()
override var inputView: UIView? {
return pickerView
}
@IBOutlet weak var regionLabel: UILabel!
@IBOutlet weak var pumpImageView: UIImageView!
}
private extension SetupButton {
func setConnectTitle() {
setTitle(LocalizedString("Connect", comment: "Button title to connect to pump during setup"), for: .normal)
}
}
|
mit
|
60f4dbc572ba2bacb550f1c9b4826770
| 32.048523 | 150 | 0.604852 | 5.521678 | false | false | false | false |
rhildreth/Cottontown
|
Cottontown/YouTubeContentViewController.swift
|
1
|
3422
|
//
// YouTubeViewController.swift
// Cottontown
//
// Created by Ron Hildreth on 3/4/16.
// Copyright © 2016 Tappdev.com. All rights reserved.
//
// Videos are now local and YouTube is not used. Also, I ran into numerous problems -
// poor handling of VoiceOver and failure to go full screen on the iPad automatically.
// I left this in so that if many additional videos are used it would not be practical to store them
// locally.
import UIKit
import AVFoundation
import AVKit
class YouTubeContentViewController: UIViewController, UIScrollViewDelegate {
var pageIndex = 0
var maxPages = 0
var youTubeID:String = ""
var youTubeText:String = ""
weak var delegate: PictureContentViewControllerDelegate?
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var youTubeTextField: UITextView!
@IBOutlet weak var videoThumbnail: UIImageView!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var leftArrow: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
playButton.accessibilityLabel = "Plays video for stop detail page \(pageIndex + 1) of \(maxPages). Swipe right for description"
youTubeTextField.text = youTubeText
pageControl.currentPage = pageIndex
pageControl.numberOfPages = maxPages
pageControl.currentPageIndicatorTintColor = UIColor.init(colorLiteralRed: 242.0/255, green: 169.0/255.0, blue: 40.0/255.0, alpha: 1.0)
// let playVars = ["rel": 0,
// "showinfo": 0,
// "modestbranding": 0,
// "playsinline": 0,
// ]
//
// player.loadWithVideoId(youTubeID, playerVars: playVars)
leftArrow.hidden = false
leftArrow.accessibilityLabel = "Goes to page \(pageIndex)"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
pageControl.isAccessibilityElement = false
delay(0.25) {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, self.playButton)
}
}
override func viewDidLayoutSubviews() {
youTubeTextField.setContentOffset(CGPointZero, animated: false)
let maxWidth = videoThumbnail.frame.width
StopsModel.resizeImage(fileName: youTubeID + "_tn", type: "jpg", maxPointSize: maxWidth) { (image) in
self.videoThumbnail.image = image
}
}
deinit {
}
@IBAction func pageControlTapped(sender: UIPageControl) {
// direction is not used in scroll based paging.
delegate?.pageControlChanged(self, newPageIndex: sender.currentPage)
}
@IBAction func leftArrowTapped(sender: UIButton) {
delegate?.pageControlChanged(self, newPageIndex: pageIndex - 1)
}
@IBAction func PlayYouTube(sender: UIButton) {
let path = NSBundle.mainBundle().pathForResource(youTubeID, ofType: "mp4")
let player = AVPlayer(URL: NSURL(fileURLWithPath: path!))
let playerController = AVPlayerViewController()
playerController.player = player
presentViewController(playerController, animated: true) {
player.play()
}
}
}
|
mit
|
2c75ad17add4cdf091df9170e75e33bb
| 29.274336 | 142 | 0.631687 | 4.98688 | false | false | false | false |
yangyueguang/MyCocoaPods
|
CarryOn/XTransitionAnimator.swift
|
1
|
33860
|
//
import UIKit
import GLKit
/// 转场方式 只使用这个就够了
public enum XTransitionType {
/// 破碎效果 present
case brokenAnim
/// 视图动画 present
case viewAnim
/// 动态动画 present
case dynamicAnim
/// 弹框动画 present
case alertAnim
/// 从天而降动画 present
case alertDropDownAnim
/// sheet动画 present
case sheetAnim
/// 放大动画 present
case scaleAnim(origionFrame: CGRect)
/// 放大动画 push... self.navigationController?.delegate = self
case navPushAnim(operation: UINavigationController.Operation)
func presentAnimation() -> UIViewControllerAnimatedTransitioning {
switch self {
case .brokenAnim: return XGLAnimator()
case .viewAnim: return XUIViewAnimator()
case .dynamicAnim: return XUIDynamicAnimator()
case .alertAnim:
return XAlertAnimatedTransition(isPresent: true)
case .alertDropDownAnim:
return XAlertDropDownAnimatedTransition(isPresent: true)
case .sheetAnim:
return XActionSheetAnimatedTransition(isPresent: true)
case .scaleAnim(origionFrame: let rec):
let scale = XScaleAnimation()
scale.originFrame = rec
scale.presenting = true
return scale
case .navPushAnim(operation: let operation):
return XScaleNavAnimation(operation: operation)
}
}
func dismissAnimation() -> UIViewControllerAnimatedTransitioning {
switch self {
case .brokenAnim: return XGLAnimator()
case .viewAnim: return XUIViewAnimator()
case .dynamicAnim: return XUIDynamicAnimator()
case .alertAnim:
return XAlertAnimatedTransition(isPresent: false)
case .alertDropDownAnim:
return XAlertDropDownAnimatedTransition(isPresent: false)
case .sheetAnim:
return XActionSheetAnimatedTransition(isPresent: false)
case .scaleAnim(origionFrame: let rec):
let scale = XScaleAnimation()
scale.originFrame = rec
scale.presenting = false
return scale
case .navPushAnim(operation: let operation):
return XScaleNavAnimation(operation: operation)
}
}
}
//FIXME: 以下不用动
private struct TexturedVertex {
var geometryVertex = Vector2()
var textureVertex = Vector2()
}
private struct TexturedQuad {
var bl = TexturedVertex()
var br = TexturedVertex()
var tl = TexturedVertex()
var tr = TexturedVertex()
}
private struct Vector2: CustomStringConvertible, Equatable {
var x : CGFloat = 0.0
var y : CGFloat = 0.0
init() {}
init(x: CGFloat ,y: CGFloat) {
self.x = x
self.y = y
}
var description: String { return "[\(x),\(y)]" }
static func + (left: Vector2, right: Vector2) -> Vector2 {
return Vector2(x:left.x + right.x, y:left.y + right.y)
}
}
private struct Sprite {
var quad = TexturedQuad()
var moveVelocity = Vector2()
mutating func slice(_ rect: CGRect, textureSize: CGSize) {
quad.bl.geometryVertex = Vector2(x: 0.0, y: 0.0)
quad.br.geometryVertex = Vector2(x: rect.size.width, y: 0)
quad.tl.geometryVertex = Vector2(x: 0, y: rect.size.height)
quad.tr.geometryVertex = Vector2(x: rect.size.width, y: rect.size.height)
quad.bl.textureVertex = Vector2(x: rect.origin.x / textureSize.width, y: rect.origin.y / textureSize.height)
quad.br.textureVertex = Vector2(x: (rect.origin.x + rect.size.width) / textureSize.width, y: rect.origin.y / textureSize.height)
quad.tl.textureVertex = Vector2(x: rect.origin.x / textureSize.width, y: (rect.origin.y + rect.size.height) / textureSize.height)
quad.tr.textureVertex = Vector2(x: (rect.origin.x + rect.size.width) / textureSize.width, y: (rect.origin.y + rect.size.height) / textureSize.height)
position = Vector2(x:position.x+rect.origin.x,y:position.y+rect.origin.y)
}
var position = Vector2() {
didSet {
let diff = Vector2(x:position.x - oldValue.x,y:position.y - oldValue.y)
quad.bl.geometryVertex = quad.bl.geometryVertex + diff
quad.br.geometryVertex = quad.br.geometryVertex + diff
quad.tl.geometryVertex = quad.tl.geometryVertex + diff
quad.tr.geometryVertex = quad.tr.geometryVertex + diff
}
}
mutating func update(_ tick: TimeInterval) {
position = Vector2(x:position.x + moveVelocity.x * CGFloat(tick),y:position.y + moveVelocity.y * CGFloat(tick))
}
}
private class SpriteRender {
fileprivate let texture: ViewTexture
fileprivate let effect: GLKBaseEffect
init(texture: ViewTexture, effect: GLKBaseEffect) {
self.texture = texture
self.effect = effect
}
func render(_ sprites: [Sprite]) {
effect.texture2d0.name = self.texture.name
effect.texture2d0.enabled = 1
effect.prepareToDraw()
var vertex = sprites.map { $0.quad }
glEnableVertexAttribArray(GLuint(GLKVertexAttrib.position.rawValue))
glEnableVertexAttribArray(GLuint(GLKVertexAttrib.texCoord0.rawValue))
withUnsafePointer(to: &vertex[0].bl.geometryVertex) { offset in
glVertexAttribPointer(GLuint(GLKVertexAttrib.position.rawValue), 2, GLenum(GL_FLOAT), GLboolean(UInt8(GL_FALSE)), GLsizei(MemoryLayout<TexturedVertex>.size), offset)
}
withUnsafePointer(to: &vertex[0].bl.textureVertex) { offset in
glVertexAttribPointer(GLuint(GLKVertexAttrib.texCoord0.rawValue), 2, GLenum(GL_FLOAT), GLboolean(UInt8(GL_FALSE)), GLsizei(MemoryLayout<TexturedVertex>.size), offset)
}
glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(vertex.count * 6))
}
}
private class ViewTexture {
var name: GLuint = 0
var width: GLsizei = 0
var height: GLsizei = 0
func setupOpenGL() {
glGenTextures(1, &name)
glBindTexture(GLenum(GL_TEXTURE_2D), name)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLint(GL_CLAMP_TO_EDGE))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLint(GL_CLAMP_TO_EDGE))
glBindTexture(GLenum(GL_TEXTURE_2D), 0);
}
deinit {
if name != 0 {
glDeleteTextures(1, &name)
}
}
func render(view: UIView) {
let scale = UIScreen.main.scale
width = GLsizei(view.layer.bounds.size.width * scale)
height = GLsizei(view.layer.bounds.size.height * scale)
var texturePixelBuffer = [GLubyte](repeating: 0, count: Int(height * width * 4))
let colorSpace = CGColorSpaceCreateDeviceRGB()
withUnsafeMutablePointer(to: &texturePixelBuffer[0]) { texturePixelBuffer in
let context = CGContext(data: texturePixelBuffer,
width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: Int(width * 4), space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)!
context.scaleBy(x: scale, y: scale)
UIGraphicsPushContext(context)
view.drawHierarchy(in: view.layer.bounds, afterScreenUpdates: false)
UIGraphicsPopContext()
glBindTexture(GLenum(GL_TEXTURE_2D), name);
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GLint(GL_RGBA), width, height, 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), texturePixelBuffer)
glBindTexture(GLenum(GL_TEXTURE_2D), 0);
}
}
}
//vc.transitioningDelegate = self
public class XGLAnimator: NSObject, UIViewControllerAnimatedTransitioning, GLKViewDelegate {
open var duration: TimeInterval = 2
open var spriteWidth: CGFloat = 8
fileprivate var sprites: [Sprite] = []
fileprivate var glContext: EAGLContext!
fileprivate var effect: GLKBaseEffect!
fileprivate var glView: GLKView!
fileprivate var displayLink: CADisplayLink!
fileprivate var lastUpdateTime: TimeInterval?
fileprivate var startTransitionTime: TimeInterval!
fileprivate var transitionContext: UIViewControllerContextTransitioning!
fileprivate var render: SpriteRender!
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!.view
let toView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!.view
containerView.addSubview(toView!)
containerView.sendSubviewToBack(toView!)
func randomFloatBetween(_ smallNumber: CGFloat, and bigNumber: CGFloat) -> Float {
let diff = bigNumber - smallNumber
return Float((CGFloat(arc4random()) / 100.0).truncatingRemainder(dividingBy: diff) + smallNumber)
}
self.glContext = EAGLContext(api: .openGLES2)
EAGLContext.setCurrent(glContext)
glView = GLKView(frame: (fromView?.frame)!, context: glContext)
glView.enableSetNeedsDisplay = true
glView.delegate = self
glView.isOpaque = false
containerView.addSubview(glView)
let texture = ViewTexture()
texture.setupOpenGL()
texture.render(view: fromView!)
effect = GLKBaseEffect()
let projectionMatrix = GLKMatrix4MakeOrtho(0, Float(texture.width), 0, Float(texture.height), -1, 1)
effect.transform.projectionMatrix = projectionMatrix
render = SpriteRender(texture: texture, effect: effect)
let size = CGSize(width: CGFloat(texture.width), height: CGFloat(texture.height))
let scale = UIScreen.main.scale
let width = spriteWidth * scale
let height = width
for x in stride(from: CGFloat(0), through: size.width, by: width) {
for y in stride(from: CGFloat(0), through: size.height, by: height) {
let region = CGRect(x: x, y: y, width: width, height: height)
var sprite = Sprite()
sprite.slice(region, textureSize: size)
sprite.moveVelocity = Vector2(x:CGFloat(randomFloatBetween(-100, and: 100)), y: CGFloat(randomFloatBetween(-CGFloat(texture.height)*1.3/CGFloat(duration), and: -CGFloat(texture.height)/CGFloat(duration))))
sprites.append(sprite)
}
}
fromView?.removeFromSuperview()
self.transitionContext = transitionContext
displayLink = CADisplayLink(target: self, selector: #selector(XGLAnimator.displayLinkTick(_:)))
displayLink.isPaused = false
displayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.common)
self.startTransitionTime = Date.timeIntervalSinceReferenceDate
}
open func animationEnded(_ transitionCompleted: Bool) {
displayLink.invalidate()
displayLink = nil
}
@objc func displayLinkTick(_ displayLink: CADisplayLink) {
if let lastUpdateTime = lastUpdateTime {
let timeSinceLastUpdate = Date.timeIntervalSinceReferenceDate - lastUpdateTime
self.lastUpdateTime = Date.timeIntervalSinceReferenceDate
for index in 0..<sprites.count {
sprites[index].update(timeSinceLastUpdate)
}
} else {
lastUpdateTime = Date.timeIntervalSinceReferenceDate
}
glView.setNeedsDisplay()
if Date.timeIntervalSinceReferenceDate - startTransitionTime > duration {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
public func glkView(_ view: GLKView, drawIn rect: CGRect) {
glClearColor(0, 0, 0, 0)
glClear(UInt32(GL_COLOR_BUFFER_BIT))
glBlendFunc(GLenum(GL_SRC_ALPHA), GLenum(GL_ONE_MINUS_SRC_ALPHA))
glEnable(GLenum(GL_BLEND))
render.render(self.sprites)
}
}
//vc.transitioningDelegate = self
public class XUIDynamicAnimator: NSObject, UIViewControllerAnimatedTransitioning {
open var duration: TimeInterval = 2
open var spriteWidth: CGFloat = 20
var transitionContext: UIViewControllerContextTransitioning!
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
var animator: UIDynamicAnimator!
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!.view
let toView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!.view
containerView.addSubview(toView!)
containerView.sendSubviewToBack(toView!)
let size = fromView!.frame.size
func randomFloatBetween(_ smallNumber: CGFloat, and bigNumber: CGFloat) -> CGFloat {
let diff = bigNumber - smallNumber
return (CGFloat(arc4random()) / 100.0).truncatingRemainder(dividingBy: diff) + smallNumber
}
let fromViewSnapshot = fromView?.snapshotView(afterScreenUpdates: false)
let width = spriteWidth
let height = width
animator = UIDynamicAnimator(referenceView: containerView)
var snapshots: [UIView] = []
for x in stride(from: CGFloat(0), through: size.width, by: width) {
for y in stride(from: CGFloat(0), through: size.height, by: height) {
let snapshotRegion = CGRect(x: x, y: y, width: width, height: height)
let snapshot = fromViewSnapshot!.resizableSnapshotView(from: snapshotRegion, afterScreenUpdates: false, withCapInsets: .zero)!
containerView.addSubview(snapshot)
snapshot.frame = snapshotRegion
snapshots.append(snapshot)
let push = UIPushBehavior(items: [snapshot], mode: .instantaneous)
push.pushDirection = CGVector(dx: randomFloatBetween(-0.15 , and: 0.15), dy: randomFloatBetween(-0.15 , and: 0))
push.active = true
animator.addBehavior(push)
}
}
let gravity = UIGravityBehavior(items: snapshots)
animator.addBehavior(gravity)
print(snapshots.count)
fromView?.removeFromSuperview()
Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(XUIDynamicAnimator.completeTransition), userInfo: nil, repeats: false)
self.transitionContext = transitionContext
}
@objc func completeTransition() {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
//vc.transitioningDelegate = self
public class XUIViewAnimator: NSObject, UIViewControllerAnimatedTransitioning {
open var duration: TimeInterval = 2
open var spriteWidth: CGFloat = 10
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let fromView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!.view
let toView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!.view
containerView.addSubview(toView!)
containerView.sendSubviewToBack(toView!)
var snapshots:[UIView] = []
let size = fromView?.frame.size
func randomFloatBetween(_ smallNumber: CGFloat, and bigNumber: CGFloat) -> CGFloat {
let diff = bigNumber - smallNumber
return (CGFloat(arc4random()) / 100.0).truncatingRemainder(dividingBy: diff) + smallNumber
}
// snapshot the from view, this makes subsequent snaphots more performant
let fromViewSnapshot = fromView?.snapshotView(afterScreenUpdates: false)
let width = spriteWidth
let height = width
for x in stride(from: CGFloat(0), through: (size?.width)!, by: width) {
for y in stride(from: CGFloat(0), through: (size?.height)!, by: height) {
let snapshotRegion = CGRect(x: x, y: y, width: width, height: height)
let snapshot = fromViewSnapshot!.resizableSnapshotView(from: snapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsets.zero)
containerView.addSubview(snapshot!)
snapshot!.frame = snapshotRegion
snapshots.append(snapshot!)
}
}
containerView.sendSubviewToBack(fromView!)
UIView.animate(withDuration:duration,delay: 0,options: UIView.AnimationOptions.curveLinear,animations: {
for view in snapshots {
let xOffset = randomFloatBetween(-200 , and: 200)
let yOffset = randomFloatBetween(fromView!.frame.height, and: fromView!.frame.height * 1.3)
view.frame = view.frame.offsetBy(dx: xOffset, dy: yOffset)
}
},completion: { _ in
for view in snapshots {
view.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
)
}
}
//vc.transitioningDelegate = self
public class XScaleAnimation: NSObject, UIViewControllerAnimatedTransitioning {
/// 图片原位置
var originFrame = CGRect.zero
/// 展示或消失
var presenting = false
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
var fromView: UIView?
var toView: UIView?
if transitionContext.responds(to: #selector(UIViewControllerContextTransitioning.view(forKey:))) {
// iOS8以上用此方法准确获取
fromView = transitionContext.view(forKey: .from)
toView = transitionContext.view(forKey: .to)
} else {
fromView = transitionContext.viewController(forKey: .from)?.view
toView = transitionContext.viewController(forKey: .to)?.view
}
let pictureView = presenting ? toView : fromView
let scaleX: CGFloat = originFrame.width / (pictureView?.frame.width ?? 1)
let scaleY: CGFloat = originFrame.height / (pictureView?.frame.height ?? 1)
let transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
let orginCenter = CGPoint(x: originFrame.midX, y: originFrame.midY)
let pictureCenter = CGPoint(x: pictureView?.frame.size.width ?? 1 / 2, y: pictureView?.frame.size.height ?? 1 / 2)
var startTransform: CGAffineTransform
var endTransform: CGAffineTransform
var startCenter: CGPoint
var endCenter: CGPoint
if presenting {
startTransform = transform
startCenter = orginCenter
endTransform = .identity
endCenter = pictureCenter
} else {
startTransform = .identity
startCenter = pictureCenter
endTransform = transform
endCenter = orginCenter
}
let container: UIView = transitionContext.containerView
container.addSubview(toView!)
container.bringSubviewToFront(pictureView!)
pictureView?.transform = startTransform
pictureView?.center = startCenter
UIView.animate(withDuration: 0.5, animations: {
pictureView?.transform = endTransform
pictureView?.center = endCenter
}) { finished in
let wasCancelled: Bool = transitionContext.transitionWasCancelled
transitionContext.completeTransition(!wasCancelled)
}
}
}
//vc.transitioningDelegate = self
public class XAlertAnimatedTransition: NSObject, UIViewControllerAnimatedTransitioning {
public var isPresent:Bool = true
required public init(isPresent:Bool){
self.isPresent = isPresent
super.init()
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresent {
presentAnimateTransition(using: transitionContext)
}else {
dismissAnimateTransition(using: transitionContext)
}
}
open func dismissAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let from = transitionContext.viewController(forKey: .from) else { return }
UIView.animate(withDuration: 0.25, delay: 0.0, options:.curveEaseInOut, animations: {
from.view.layer.opacity = 0.0
from.view.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
public func presentAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let to = transitionContext.viewController(forKey: .to) else { return }
let containerView = transitionContext.containerView
to.view.frame = to.presentationController!.frameOfPresentedViewInContainerView
containerView.addSubview(to.view)
to.view.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.25, delay: 0.0, options:.curveEaseInOut, animations: {
to.view.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
}) { _ in
UIView.animate(withDuration: 0.2, delay: 0.0, options:.curveEaseInOut, animations: {
to.view.transform = CGAffineTransform.identity
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
}
//vc.transitioningDelegate = self
public class XAlertDropDownAnimatedTransition: NSObject, UIViewControllerAnimatedTransitioning {
public var isPresent:Bool = true
required public init(isPresent:Bool){
self.isPresent = isPresent
super.init()
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresent {
presentAnimateTransition(using: transitionContext)
}else {
dismissAnimateTransition(using: transitionContext)
}
}
open func dismissAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let from = transitionContext.viewController(forKey: .from) else { return }
UIView.animate(withDuration: 0.25, delay: 0.0, options:.curveEaseInOut, animations: {
from.view.layer.opacity = 0.0
from.view.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
public func presentAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let to = transitionContext.viewController(forKey: .to) else { return }
let containerView = transitionContext.containerView
to.view.frame = to.presentationController!.frameOfPresentedViewInContainerView
containerView.addSubview(to.view)
to.view.transform = CGAffineTransform(translationX: 0.0, y: -to.view.frame.maxY)
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.65, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
to.view.transform = CGAffineTransform.identity
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
//vc.transitioningDelegate = self
public class XActionSheetAnimatedTransition: NSObject, UIViewControllerAnimatedTransitioning {
public var isPresent:Bool = true
required public init(isPresent:Bool){
super.init()
}
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresent {
presentAnimateTransition(using: transitionContext)
}else {
dismissAnimateTransition(using: transitionContext)
}
}
open func dismissAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let from = transitionContext.viewController(forKey: .from) else { return }
UIView.animate(withDuration: 0.25, delay: 0.0, options:.curveEaseInOut, animations: {
from.view.layer.opacity = 0.0
from.view.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
public func presentAnimateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard var from = transitionContext.viewController(forKey: .from),
var to = transitionContext.viewController(forKey: .to)
else { return }
let containerView = transitionContext.containerView
let duration = self.transitionDuration(using: transitionContext)
var start = CGAffineTransform(translationX: 0.0, y: to.view.frame.height)
var end = CGAffineTransform.identity
if isPresent == false {
swap(&from, &to)
swap(&start, &end)
}else{
/// 只有在 present 时候 需要将 to.view 添加到 containerView
to.view.frame = to.presentationController!.frameOfPresentedViewInContainerView
containerView.addSubview(to.view)
}
to.view.transform = start
UIView.animate(withDuration: duration, delay: 0.0, options:UIView.AnimationOptions(rawValue: 7 << 16 | UIView.AnimationOptions.allowAnimatedContent.rawValue), animations: {
to.view.transform = end
}) { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
//FIXME: Navigation 转场,需要遵守下面代理并设置self.navigationController?.delegate = self
@objc protocol Animatable {
var containerView: UIView? { get }
var childView: UIView? { get }
@available(iOS 10.0, *)
@objc optional func presentingView(
sizeAnimator: UIViewPropertyAnimator,
positionAnimator: UIViewPropertyAnimator,
fromFrame: CGRect,
toFrame: CGRect
)
@available(iOS 10.0, *)
@objc optional func dismissingView(
sizeAnimator: UIViewPropertyAnimator,
positionAnimator: UIViewPropertyAnimator,
fromFrame: CGRect,
toFrame: CGRect
)
}
public class XScaleNavAnimation: NSObject {
fileprivate let operationType: UINavigationController.Operation
fileprivate let positioningDuration: TimeInterval = 1
fileprivate let resizingDuration: TimeInterval = 0.5
init(operation: UINavigationController.Operation) {
self.operationType = operation
}
internal func presentTransition(_ transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let fromVC = transitionContext.viewController(forKey: .from) as? Animatable, let fromContainer = fromVC.containerView,
let fromChild = fromVC.childView else { return }
guard
let toVC = transitionContext.viewController(forKey: .to) as? Animatable,
let toView = transitionContext.view(forKey: .to) else { return }
let originalFrame = toView.frame
container.addSubview(toView)
let originFrame = CGRect(origin: fromContainer.convert(fromChild.frame.origin, to: container),size: fromChild.frame.size)
let destinationFrame = toView.frame
toView.frame = originFrame
toView.layoutIfNeeded()
fromChild.isHidden = true
let yDiff = destinationFrame.origin.y - originFrame.origin.y
let xDiff = destinationFrame.origin.x - originFrame.origin.x
if #available(iOS 10.0, *) {
let positionAnimator = UIViewPropertyAnimator(duration: self.positioningDuration, dampingRatio: 0.7)
positionAnimator.addAnimations {
toView.transform = CGAffineTransform(translationX: 0, y: yDiff)
}
let sizeAnimator = UIViewPropertyAnimator(duration: self.resizingDuration, curve: .easeInOut)
sizeAnimator.addAnimations {
toView.frame.size = destinationFrame.size
toView.layoutIfNeeded()
toView.transform = toView.transform.concatenating(CGAffineTransform(translationX: xDiff, y: 0))
}
toVC.presentingView?(
sizeAnimator: sizeAnimator,
positionAnimator: positionAnimator,
fromFrame: originFrame,
toFrame: destinationFrame
)
let completionHandler: (UIViewAnimatingPosition) -> Void = { _ in
toView.transform = .identity
toView.frame = originalFrame
toView.layoutIfNeeded()
fromChild.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
if (self.positioningDuration > self.resizingDuration) {
positionAnimator.addCompletion(completionHandler)
} else {
sizeAnimator.addCompletion(completionHandler)
}
positionAnimator.startAnimation()
sizeAnimator.startAnimation()
} else {
}
}
internal func dismissTransition(_ transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard
let fromVC = transitionContext.viewController(forKey: .from) as? Animatable,
let fromView = transitionContext.view(forKey: .from)
else { return }
guard
let toVC = transitionContext.viewController(forKey: .to) as? Animatable,
let toView = transitionContext.view(forKey: .to),
let toContainer = toVC.containerView,
let toChild = toVC.childView
else { return }
container.addSubview(toView)
container.addSubview(fromView)
let originFrame = fromView.frame
let destinationFrame = CGRect(
origin: toContainer.convert(toChild.frame.origin, to: container),
size: toChild.frame.size
)
toChild.isHidden = true
let yDiff = destinationFrame.origin.y - originFrame.origin.y
let xDiff = destinationFrame.origin.x - originFrame.origin.x
if #available(iOS 10.0, *) {
let positionAnimator = UIViewPropertyAnimator(duration: self.positioningDuration, dampingRatio: 0.7)
positionAnimator.addAnimations {
fromView.transform = CGAffineTransform(translationX: 0, y: yDiff)
}
let sizeAnimator = UIViewPropertyAnimator(duration: self.resizingDuration, curve: .easeInOut)
sizeAnimator.addAnimations {
fromView.frame.size = destinationFrame.size
fromView.layoutIfNeeded()
fromView.transform = fromView.transform.concatenating(CGAffineTransform(translationX: xDiff, y: 0))
}
fromVC.dismissingView?(
sizeAnimator: sizeAnimator,
positionAnimator: positionAnimator,
fromFrame: originFrame,
toFrame: destinationFrame
)
let completionHandler: (UIViewAnimatingPosition) -> Void = { _ in
fromView.removeFromSuperview()
toChild.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
if (self.positioningDuration > self.resizingDuration) {
positionAnimator.addCompletion(completionHandler)
} else {
sizeAnimator.addCompletion(completionHandler)
}
positionAnimator.startAnimation()
sizeAnimator.startAnimation()
} else {
}
}
}
extension XScaleNavAnimation: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return max(self.resizingDuration, self.positioningDuration)
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if self.operationType == .push {
self.presentTransition(transitionContext)
} else if self.operationType == .pop {
self.dismissTransition(transitionContext)
}
}
}
|
mit
|
49a52d3f107e5e8524cfe8fd8f564c9d
| 44.260753 | 221 | 0.6693 | 5.052363 | false | false | false | false |
vuchau/ioscreator
|
IOS8SwiftLocalNotificationTutorial/IOS8SwiftLocalNotificationTutorial/ViewController.swift
|
40
|
1085
|
//
// ViewController.swift
// IOS8SwiftLocalNotificationTutorial
//
// Created by Arthur Knopper on 27/01/15.
// Copyright (c) 2015 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func sendNotification(sender: UIButton) {
var localNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
localNotification.alertBody = "new Blog Posted at iOScreator.com"
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
b41874549c48337e2e99eed3a11e4278
| 30 | 119 | 0.717972 | 5.564103 | false | false | false | false |
xhamr/fave-button
|
Source/Helpers/Constraints+.swift
|
1
|
4597
|
//
// Constraints+.swift
// FaveButton
//
// Copyright © 2016 Jansel Valentin.
//
// 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
precedencegroup ConstrPrecedence {
associativity: left
higherThan: AssignmentPrecedence
}
//infix operator >>- { associativity left precedence 160 }
infix operator >>- : ConstrPrecedence
struct Constraint{
var identifier: String?
#if swift(>=4.2)
var attribute: NSLayoutConstraint.Attribute = .centerX
var secondAttribute: NSLayoutConstraint.Attribute = .notAnAttribute
#else
var attribute: NSLayoutAttribute = .centerX
var secondAttribute: NSLayoutAttribute = .notAnAttribute
#endif
var constant: CGFloat = 0
var multiplier: CGFloat = 1
#if swift(>=4.2)
var relation: NSLayoutConstraint.Relation = .equal
#else
var relation: NSLayoutRelation = .equal
#endif
}
#if swift(>=4.2)
func attributes(_ attrs:NSLayoutConstraint.Attribute...) -> [NSLayoutConstraint.Attribute]{
return attrs
}
#else
func attributes(_ attrs:NSLayoutAttribute...) -> [NSLayoutAttribute]{
return attrs
}
#endif
@discardableResult func >>- <T: UIView> (lhs: (T,T), apply: (inout Constraint) -> () ) -> NSLayoutConstraint {
var const = Constraint()
apply(&const)
const.secondAttribute = .notAnAttribute == const.secondAttribute ? const.attribute : const.secondAttribute
let constraint = NSLayoutConstraint(item: lhs.0,
attribute: const.attribute,
relatedBy: const.relation,
toItem: lhs.1,
attribute: const.secondAttribute,
multiplier: const.multiplier,
constant: const.constant)
constraint.identifier = const.identifier
NSLayoutConstraint.activate([constraint])
return constraint
}
@discardableResult func >>- <T: UIView> (lhs: T, apply: (inout Constraint) -> () ) -> NSLayoutConstraint {
var const = Constraint()
apply(&const)
let constraint = NSLayoutConstraint(item: lhs,
attribute: const.attribute,
relatedBy: const.relation,
toItem: nil,
attribute: const.attribute,
multiplier: const.multiplier,
constant: const.constant)
constraint.identifier = const.identifier
NSLayoutConstraint.activate([constraint])
return constraint
}
#if swift(>=4.2)
func >>- <T:UIView> (lhs: (T,T),attributes: [NSLayoutConstraint.Attribute]){
for attribute in attributes{
lhs >>- { (i: inout Constraint) in
i.attribute = attribute
}
}
}
#else
func >>- <T:UIView> (lhs: (T,T),attributes: [NSLayoutAttribute]){
for attribute in attributes{
lhs >>- { (i: inout Constraint) in
i.attribute = attribute
}
}
}
#endif
#if swift(>=4.2)
func >>- <T:UIView> (lhs: T, attributes: [NSLayoutConstraint.Attribute]){
for attribute in attributes{
lhs >>- { (i: inout Constraint) in
i.attribute = attribute
}
}
}
#else
func >>- <T:UIView> (lhs: T, attributes: [NSLayoutAttribute]){
for attribute in attributes{
lhs >>- { (i: inout Constraint) in
i.attribute = attribute
}
}
}
#endif
|
mit
|
f6eb33cb49cc4228e0e3dad29a23dd0b
| 31.595745 | 110 | 0.62054 | 4.93133 | false | false | false | false |
Tj3n/TVNExtensions
|
Helper/ImageViewerViewController.swift
|
1
|
12508
|
//
// ImageViewerViewController.swift
//
// Created by TienVu on 11/6/18.
//
import UIKit
import AVFoundation
#if canImport(Kingfisher)
import Kingfisher
#endif
/// Full screen Image Viewer, to handle URL with Kingfisher add to podfile: pod 'TVNExtensions/Kingfisher'
public class ImageViewerViewController: UIViewController {
private lazy var scrollView: UIScrollView = {
let v = UIScrollView(frame: .zero)
v.delegate = self
v.alwaysBounceVertical = true
v.alwaysBounceHorizontal = true
v.bounces = true
v.bouncesZoom = true
v.showsVerticalScrollIndicator = false
v.showsHorizontalScrollIndicator = false
return v
}()
private lazy var imageView: UIImageView = {
let v = UIImageView(frame: .zero)
v.image = image
v.contentMode = .scaleAspectFit
v.isUserInteractionEnabled = true
v.addGestureRecognizer(panGesture)
v.addGestureRecognizer(doubleTapGesture)
panGesture.delegate = self
return v
}()
private lazy var panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
private lazy var doubleTapGesture: UITapGestureRecognizer = {
let g = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapGesture(_:)))
g.numberOfTapsRequired = 2
return g
}()
private lazy var blurredView: UIVisualEffectView = {
let v = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
return v
}()
private lazy var closeBtn: UIButton = {
var v: UIButton
if #available(iOS 13.0, *) {
v = UIButton(type: .close)
} else {
v = UIButton(type: .roundedRect)
v.setTitle("X", for: .normal)
v.tintColor = .white
v.borderWidth = 1
v.borderColor = .white
v.cornerRadius = 15
}
v.addTarget(self, action: #selector(closeBtnTouch(_:)), for: .touchUpInside)
return v
}()
private var image: UIImage?
private lazy var originalPosition: CGPoint = view.center
private var imageURL: URL?
private var animator: ImageViewerAnimator?
// private var isZooming = false
// var shouldDismiss = false
private var downloadedImgCompletion: ((UIImage?) -> ())?
/// Create imageViewer with transition animation from view/imageview/cell...
///
/// - Parameters:
/// - image: image
/// - view: starting view
/// - clippingTransition: Set to false if the from view has bound clipping
convenience public init(image: UIImage?, from view: UIView?, clippingTransition: Bool = true) {
self.init(nibName:nil, bundle:nil)
self.image = image
setupModalPresention(from: view, image: image, clippingTransition: clippingTransition)
}
/// Create imageViewer from URL with transition animation from view/imageview/cell...
///
/// - Parameters:
/// - imageURL: image URL
/// - placeholderImage: placeholder image, can be nil
/// - view: starting view
/// - clippingTransition: Set to false if the from view has bound clipping
/// - completion: completion closure after finished image downloading
convenience public init(imageURL: URL, placeholderImage: UIImage?, from view: UIView?, clippingTransition: Bool = true, completion: ((UIImage?) -> ())?) {
self.init(nibName:nil, bundle:nil)
self.imageURL = imageURL
self.image = placeholderImage
self.downloadedImgCompletion = completion
setupModalPresention(from: view, image: placeholderImage, clippingTransition: clippingTransition)
}
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupView()
calculateZoomScale()
if let url = imageURL {
#if canImport(Kingfisher)
self.imageView.kf.indicatorType = .activity
self.imageView.kf.setImage(with: url, placeholder: image, options: nil, progressBlock: nil) { [weak self] (img, _, _, _) in
self?.image = img
self?.calculateZoomScale()
self?.downloadedImgCompletion?(img)
}
#else
DispatchQueue.global().async {
if let imageData = try? Data(contentsOf: url) {
DispatchQueue.main.async { [weak self] in
let newImage = UIImage(data: imageData)
self?.image = newImage
self?.imageView.image = newImage
self?.calculateZoomScale()
self?.downloadedImgCompletion?(newImage)
}
}
}
#endif
}
}
override public var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
private func setupModalPresention(from view: UIView?, image: UIImage?, clippingTransition: Bool) {
modalPresentationStyle = .overFullScreen
modalTransitionStyle = .crossDissolve
modalPresentationCapturesStatusBarAppearance = true
guard let view = view, let image = image else { return }
animator = ImageViewerAnimator(from: view, image: image, clippingTransition: clippingTransition)
transitioningDelegate = animator
}
private func setupView() {
if #available(iOS 11.0, *) {
scrollView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
view.addSubview(blurredView)
view.addSubview(scrollView)
scrollView.addSubview(imageView)
view.addSubview(closeBtn)
blurredView.edgesToSuperView()
scrollView.edgesToSuperView()
imageView.edgesToSuperView()
imageView.setRelativeWidth(to: view)
imageView.setRelativeHeight(to: view)
closeBtn.topMargin(to: view, by: 16)
closeBtn.right(to: view, by: 16)
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .dark //Light mode for close button will be hard to see
} else {
closeBtn.setWidth(30)
closeBtn.setHeight(30)
}
}
@objc func closeBtnTouch(_ sender: UIButton) {
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
if #available(iOS 13.0, *) {
self.imageView.transform = CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.height)
} else {
self.imageView.layer.frame.origin = CGPoint(x: self.view.frame.origin.x, y: self.view.frame.size.height)
}
}) { (isCompleted) in
if isCompleted {
self.animator?.prepareForDismiss(from: self.imageView)
self.dismiss(animated: true, completion: nil)
}
}
}
/// If horizontal image then get max zoom by height, else by width
private func calculateZoomScale() {
scrollView.minimumZoomScale = 1
guard let image = image else { return }
let imageViewSize = aspectFitRect(forSize: image.size, insideRect: UIScreen.main.bounds)
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
scrollView.maximumZoomScale = max(screenWidth / imageViewSize.width, screenHeight / imageViewSize.height)
}
@objc private func handleDoubleTapGesture(_ tapGesture: UITapGestureRecognizer) {
if scrollView.zoomScale > scrollView.minimumZoomScale {
scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
} else {
let position = tapGesture.location(in: tapGesture.view)
let zoomRect = calculateZoomRect(scale: scrollView.maximumZoomScale, center: position)
scrollView.zoom(to: zoomRect, animated: true)
}
}
@objc private func handleGesture(_ panGesture: UIPanGestureRecognizer) {
let translation = panGesture.translation(in: view)
switch panGesture.state {
case .began:
originalPosition = imageView.center
break
case .changed:
imageView.frame.origin = CGPoint(x: translation.x, y: translation.y)
break
case .ended:
let velocity = panGesture.velocity(in: view)
if velocity.y >= 1500 {
if #available(iOS 13.0, *) {
self.imageView.transform = CGAffineTransform(translationX: translation.x, y: translation.y).concatenating(CGAffineTransform(scaleX: scrollView.zoomScale, y: scrollView.zoomScale))
}
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
if #available(iOS 13.0, *) {
self.imageView.transform = CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.height)
} else {
self.imageView.layer.frame.origin = CGPoint(x: self.view.frame.origin.x, y: self.imageView.frame.size.height)
}
}) { (isCompleted) in
if isCompleted {
self.animator?.prepareForDismiss(from: self.imageView)
self.dismiss(animated: true, completion: nil)
}
}
} else {
UIView.animate(withDuration: 0.2, animations: {
self.imageView.center = self.originalPosition
})
}
default:
break
}
}
}
//MARK: Helper
extension ImageViewerViewController {
func calculateZoomRect(scale: CGFloat, center: CGPoint) -> CGRect {
var zoomRect = CGRect.zero
zoomRect.size.height = imageView.frame.size.height / scale
zoomRect.size.width = imageView.frame.size.width / scale
let newCenter = scrollView.convert(center, from: imageView)
zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0)
return zoomRect
}
func aspectFitRect(forSize size: CGSize, insideRect: CGRect) -> CGRect {
return AVMakeRect(aspectRatio: size, insideRect: insideRect)
}
}
//MARK:
extension ImageViewerViewController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if #available(iOS 13, *) {
if (gestureRecognizer is UIPanGestureRecognizer || gestureRecognizer is UIRotationGestureRecognizer) {
return true
}
}
return false
}
}
//MARK: UIScrollViewDelegate
extension ImageViewerViewController: UIScrollViewDelegate {
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
guard let image = imageView.image else { return }
let imageViewSize = aspectFitRect(forSize: image.size, insideRect: imageView.frame)
let verticalInsets = -(scrollView.contentSize.height - max(imageViewSize.height, scrollView.bounds.height)) / 2
let horizontalInsets = -(scrollView.contentSize.width - max(imageViewSize.width, scrollView.bounds.width)) / 2
scrollView.contentInset = UIEdgeInsets(top: verticalInsets, left: horizontalInsets, bottom: verticalInsets, right: horizontalInsets)
// isZooming = scrollView.contentInset == .zero
}
// func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
// print(velocity)
// if velocity.y > 2 || velocity.y < -2 {
// shouldDismiss = true
// } else {
// shouldDismiss = false
// }
// }
//
// func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// if shouldDismiss {
// self.dismiss(animated: true, completion: nil)
// }
// }
}
|
mit
|
84f4a108d8ac465f4bbd21d4b239c505
| 39.61039 | 199 | 0.617205 | 5.124129 | false | false | false | false |
shoheiyokoyama/Gemini
|
Example/Gemini/ViewControllers/CustomAnimationViewController.swift
|
1
|
5256
|
import UIKit
import Gemini
enum CustomAnimationType {
case custom1
case custom2
fileprivate func layout(withParentView parentView: UIView) -> UICollectionViewFlowLayout {
switch self {
case .custom1:
let layout = UICollectionViewPagingFlowLayout()
layout.itemSize = CGSize(width: parentView.bounds.width - 100, height: parentView.bounds.height - 200)
layout.sectionInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 50)
layout.minimumLineSpacing = 10
layout.scrollDirection = .horizontal
return layout
case .custom2:
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 150, height: 150)
layout.sectionInset = UIEdgeInsets(top: 15,
left: (parentView.bounds.width - 150) / 2,
bottom: 15,
right: (parentView.bounds.width - 150) / 2)
layout.minimumLineSpacing = 15
layout.scrollDirection = .vertical
return layout
}
}
}
final class CustomAnimationViewController: UIViewController {
@IBOutlet private weak var collectionView: GeminiCollectionView! {
didSet {
let nib = UINib(nibName: cellIdentifier, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
}
}
}
private let cellIdentifier = String(describing: ImageCollectionViewCell.self)
private let images = Resource.image.images
private var animationType = CustomAnimationType.custom2
static func make(animationType: CustomAnimationType) -> CustomAnimationViewController {
let storyboard = UIStoryboard(name: "CustomAnimationViewController", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "CustomAnimationViewController") as! CustomAnimationViewController
viewController.animationType = animationType
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(true, animated: false)
let gesture = UITapGestureRecognizer(target: self, action: #selector(toggleNavigationBarHidden(_:)))
gesture.cancelsTouchesInView = false
view.addGestureRecognizer(gesture)
switch animationType {
case .custom1:
collectionView.collectionViewLayout = animationType.layout(withParentView: view)
collectionView.decelerationRate = UIScrollView.DecelerationRate.fast
collectionView.gemini
.customAnimation()
.translation(y: 50)
.rotationAngle(y: 13)
.ease(.easeOutExpo)
.shadowEffect(.fadeIn)
.maxShadowAlpha(0.3)
case .custom2:
collectionView.collectionViewLayout = animationType.layout(withParentView: view)
collectionView.gemini
.customAnimation()
.backgroundColor(startColor: UIColor(red: 38 / 255, green: 194 / 255, blue: 129 / 255, alpha: 1),
endColor: UIColor(red: 89 / 255, green: 171 / 255, blue: 227 / 255, alpha: 1))
.ease(.easeOutSine)
.cornerRadius(75)
}
}
@objc private func toggleNavigationBarHidden(_ gestureRecognizer: UITapGestureRecognizer) {
let isNavigationBarHidden = navigationController?.isNavigationBarHidden ?? true
navigationController?.setNavigationBarHidden(!isNavigationBarHidden, animated: true)
}
}
// MARK: - UIScrollViewDelegate
extension CustomAnimationViewController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
collectionView.animateVisibleCells()
}
}
// MARK: - UICollectionViewDelegate
extension CustomAnimationViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? GeminiCell {
self.collectionView.animateCell(cell)
}
}
}
// MARK: - UICollectionViewDataSource
extension CustomAnimationViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ImageCollectionViewCell
if animationType == .custom1 {
cell.configure(with: images[indexPath.row])
}
self.collectionView.animateCell(cell)
return cell
}
}
|
mit
|
4d8973a972a1571a205baebde90b0fbc
| 38.518797 | 148 | 0.656773 | 5.879195 | false | false | false | false |
idmean/CodaLess
|
CodaLess/CodaLess.swift
|
1
|
6140
|
//
// CodaLess.swift
// CodaLess
//
// Created by Theo on 05/12/14.
// Copyright (c) 2014 Theo Weidmann. All rights reserved.
//
import AppKit
import Foundation
class CodaLess: NSObject, CodaPlugIn {
var bundle: CodaPlugInBundle
var preferences: CodaLessPrefrencesWindowController?
let userDefaults = UserDefaults.standard
required init!(plugIn aController: CodaPlugInsController!, plugInBundle: CodaPlugInBundle!) {
bundle = plugInBundle
userDefaults.register(defaults: [
"cssPath": "{path}/{basename}.css",
"jsPath": "{path}/{basename}.js",
"cleanCSS": false
])
super.init()
aController.registerAction(withTitle: "CodaLess Preferences", underSubmenuWithTitle: nil, target: self, selector: #selector(CodaLess.showPreferences), representedObject: nil, keyEquivalent: nil, pluginName: name())
if !FileManager.default.fileExists(atPath: "/usr/local/bin/node") {
DispatchQueue.main.async {
let alert = NSAlert()
alert.messageText = "CodaLess: Node not found"
alert.informativeText = "Node could not be found at /usr/local/bin/node."
alert.runModal()
}
}
if userDefaults.bool(forKey: "minify") {
DispatchQueue.main.async(execute: { () -> Void in
let alert = NSAlert()
alert.messageText = "CodaLess: Less minify deprecation"
alert.informativeText = "The less developers deprecated the minify option. Therefore the minify option was removed, however you can now choose to enable the Clean CSS plugin in the preferences."
alert.runModal()
})
userDefaults.removeObject(forKey: "minify")
}
}
required init!(plugIn aController: CodaPlugInsController!, bundle plugInBundle: Bundle!) {
fatalError("Not compatible with this version of Coda.")
}
func name() -> String! {
return "CodaLess"
}
func textViewWillSave(_ textView: CodaTextView!) {
guard let path = textView.path() else {
return
}
let url = URL(fileURLWithPath: path)
if url.pathExtension != "less" || (url.pathComponents[2] == "Coda 2" && url.pathComponents[3] == "Caches") {
return
}
let destination = url.deletingLastPathComponent().path
let basename = url.deletingPathExtension().lastPathComponent
if let format = userDefaults.string(forKey: "cssPath") {
let cssPath = format.replacingOccurrences(of: "{path}", with: destination, options: NSString.CompareOptions.literal, range: nil).replacingOccurrences(of: "{basename}", with: basename, options: NSString.CompareOptions.literal, range: nil)
let task = Process()
task.launchPath = "/usr/local/bin/node"
var args = ["/usr/local/lib/node_modules/less/bin/lessc", path, cssPath, "--no-color"]
if userDefaults.bool(forKey: "cleanCSS") {
args.append("--clean-css")
}
task.arguments = args
let outputPipe = Pipe()
task.standardError = outputPipe
task.terminationHandler = { (task: Process) in
let string = NSString(data: outputPipe.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue)
if string != nil && string!.length > 0 {
let alert = NSAlert()
alert.messageText = "LESS Compilation Error"
alert.informativeText = string as! String
alert.addButton(withTitle: "OK")
let regex: NSRegularExpression?
do {
regex = try NSRegularExpression(pattern: "line (\\d+), column (\\d+)", options: NSRegularExpression.Options.caseInsensitive)
}
catch {
regex = nil
}
var errLine: Int?
var errCol: Int?
if let regex = regex {
let match = regex.firstMatch(in: string as! String, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: string!.length))
if let match = match {
errLine = Int(string!.substring(with: match.rangeAt(1)))
errCol = Int(string!.substring(with: match.rangeAt(2)))
alert.addButton(withTitle: "Jump to error")
}
}
DispatchQueue.main.async {
if alert.runModal() == NSAlertSecondButtonReturn {
if errLine != nil && errCol != nil {
textView.go(toLine: errLine!, column: errCol!)
}
else {
let alert = NSAlert()
alert.messageText = "Could not determine error position"
alert.informativeText = "CodaLess was not able to determine the position of the error. Please submit an issue on https://github.com/idmean/CodaLess/issues including your less version!"
alert.runModal()
}
}
return
}
}
}
task.launch()
}
}
func showPreferences(){
if preferences == nil {
preferences = CodaLessPrefrencesWindowController(windowNibName: "CodaLessPreferencesWindowController")
}
preferences!.showWindow(self)
}
}
|
gpl-3.0
|
d5150daeae5e133e526518c95278822a
| 40.768707 | 249 | 0.524267 | 5.381245 | false | false | false | false |
audiokit/AudioKit
|
Sources/AudioKit/Internals/Microtonality/TuningTable.swift
|
2
|
9186
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import Foundation
/// helper object to simulate a Swift tuple for ObjC interoperability
public class TuningTableETNN: NSObject {
/// MIDI Note Nubmer
public var nn: MIDINoteNumber = 60
/// Pitch Bend
public var pitchBend: Int = 16_384 / 2
/// Initial tuning table with note number and pitch Bend
/// - Parameters:
/// - nn: Note Number
/// - pb: Pitch Bend
public init(_ nn: MIDINoteNumber = 60, _ pb: Int = 16_384 / 2) {
self.nn = nn
self.pitchBend = pb
}
}
/// helper object to simulate a Swift tuple for ObjC interoperability
public class TuningTableDelta12ET: NSObject {
/// MIDI note number
public var nn: MIDINoteNumber = 60
/// Detuning in cents
public var cents: Double = 0
/// Initialize tuning table
/// - Parameters:
/// - nn: Note number
/// - cents: Detuning cents
public init(_ nn: MIDINoteNumber = 60, _ cents: Double = 0) {
self.nn = nn
self.cents = cents
}
}
/// TuningTable provides high-level methods to create musically useful tuning tables
public class TuningTable: TuningTableBase {
/// an octave-based array of linear frequencies, processed to spread across all midi note numbers
public private(set) var masterSet = [Frequency]()
/// Note number for standard reference note
public var middleCNoteNumber: MIDINoteNumber = 60 {
didSet {
updateTuningTableFromMasterSet()
}
}
/// Frequency of standard reference note
/// equivalent to noteToHz: return 440. * exp2((60 - 69)/12.)
public var middleCFrequency: Frequency = 261.625_565_300_6 {
didSet {
updateTuningTableFromMasterSet()
}
}
/// Octave number for standard reference note. Can be negative
/// ..., -2, -1, 0, 1, 2, ...
public var middleCOctave: Int = 0 {
didSet {
updateTuningTableFromMasterSet()
}
}
/// Range of downwards Pitch Bend used in etNN calculation. Must match your synthesizer's pitch bend DOWN range
/// etNNPitchBendRangeDown and etNNPitchBendRangeUp must cover a spread that is
/// greater than the maximum distance between two notes in your octave.
public var etNNPitchBendRangeDown: Cents = -50 {
didSet {
updateTuningTableFromMasterSet()
}
}
internal let pitchBendLow: Double = 0
/// Range of upwards Pitch Bend used in etNN calculation. Must match your synthesizer's pitch bend UP range
/// etNNPitchBendRangeDown and etNNPitchBendRangeUp must cover a spread that is
/// greater than the maximum distance between two notes in your octave.
public var etNNPitchBendRangeUp: Cents = 50 {
didSet {
updateTuningTableFromMasterSet()
}
}
internal let pitchBendHigh: Double = 16_383
internal var etNNDictionary = [MIDINoteNumber: TuningTableETNN]()
/// Given the tuning table's MIDINoteNumber NN return an TuningTableETNN
/// of the equivalent 12ET MIDINoteNumber plus Pitch Bend
/// Returns nil if the tuning table's MIDINoteNumber cannot be mapped to 12ET
/// - parameter nn: The tuning table's Note Number
public func etNNPitchBend(NN nn: MIDINoteNumber) -> TuningTableETNN? {
return etNNDictionary[nn]
}
internal var delta12ETDictionary = [MIDINoteNumber: TuningTableDelta12ET]()
/// Given the tuning table's MIDINoteNumber NN return an
/// TuningTableETNN of the equivalent 12ET MIDINoteNumber plus Pitch Bend
/// Returns nil if the tuning table's MIDINoteNumber cannot be mapped to 12ET
/// - parameter nn: The tuning table's Note Number
public func delta12ET(NN nn: MIDINoteNumber) -> TuningTableDelta12ET? {
return delta12ETDictionary[nn]
}
/// Notes Per Octave: The count of the masterSet array
override public var npo: Int {
return masterSet.count
}
/// Initialization for standard default 12 tone equal temperament
override public init() {
super.init()
_ = defaultTuning()
}
/// Create the tuning using the input masterSet
///
/// - parameter inputMasterSet: An array of frequencies, i.e., the "masterSet"
///
@discardableResult public func tuningTable(fromFrequencies inputMasterSet: [Frequency]) -> Int {
if inputMasterSet.isEmpty {
Log("No input frequencies")
return 0
}
// octave reduce
var frequenciesAreValid = true
let frequenciesOctaveReduce = inputMasterSet.map { (frequency: Frequency) -> Frequency in
if frequency == 0 {
frequenciesAreValid = false
return Frequency(1)
}
var l2 = abs(frequency)
while l2 < 1 {
l2 *= 2.0
}
while l2 >= 2 {
l2 /= 2.0
}
return l2
}
if !frequenciesAreValid {
Log("Invalid input frequencies")
return 0
}
// sort
let frequenciesOctaveReducedSorted = frequenciesOctaveReduce.sorted { $0 < $1 }
masterSet = frequenciesOctaveReducedSorted
// update
updateTuningTableFromMasterSet()
return masterSet.count
}
/// Create the tuning based on deviations from 12ET by an array of cents
///
/// - parameter centsArray: An array of 12 Cents.
/// 12ET will be modified by the centsArray, including deviations which result in a root less than 1.0
///
public func tuning12ETDeviation(centsArray: [Cents]) {
// Cents array count must equal 12
guard centsArray.count == 12 else {
Log("user error: centsArray must have 12 elements")
return
}
// 12ET
_ = twelveToneEqualTemperament()
// This should never happen
guard masterSet.count == 12 else {
Log("internal error: 12 et must have 12 tones")
return
}
// Master Set is in Frequency space
var masterSetProcessed = masterSet
// Scale by cents => Frequency space
for (index, cent) in centsArray.enumerated() {
let centF = exp2(cent / 1_200)
masterSetProcessed[index] = masterSetProcessed[index] * centF
}
masterSet = masterSetProcessed
// update
updateTuningTableFromMasterSet()
}
// Assume masterSet is set and valid: Process and update tuning table.
internal func updateTuningTableFromMasterSet() {
etNNDictionary.removeAll(keepingCapacity: true)
delta12ETDictionary.removeAll(keepingCapacity: true)
for i in 0 ..< TuningTable.midiNoteCount {
let ff = Frequency(i - Int(middleCNoteNumber)) / Frequency(masterSet.count)
var ttOctaveFactor = Frequency(trunc(ff))
if ff < 0 {
ttOctaveFactor -= 1
}
var frac = fabs(ttOctaveFactor - ff)
if frac == 1 {
frac = 0
ttOctaveFactor += 1
}
let frequencyIndex = Int(round(frac * Frequency(masterSet.count)))
let tone = Frequency(masterSet[frequencyIndex])
let lp2 = pow(2, ttOctaveFactor)
var f = tone * lp2 * middleCFrequency
f = (0 ... TuningTable.NYQUIST).clamp(f)
tableData[i] = Frequency(f)
// UPDATE etNNPitchBend
if f <= 0 { continue } // defensive, in case clamp above is removed
let freqAs12ETNN = Double(middleCNoteNumber) + 12 * log2(f / middleCFrequency)
if freqAs12ETNN >= 0, freqAs12ETNN < Double(TuningTable.midiNoteCount) {
let etnnt = modf(freqAs12ETNN)
var nnAs12ETNN = MIDINoteNumber(etnnt.0) // integer part "12ET note number"
var etnnpbf = 100 * etnnt.1 // convert fractional part to Cents
// if fractional part is [0.5,1.0] then flip it: add one to note number and negate pitchbend.
if etnnpbf >= 50, nnAs12ETNN < MIDINoteNumber(TuningTable.midiNoteCount - 1) {
nnAs12ETNN += 1
etnnpbf -= 100
}
let delta12ETpbf = etnnpbf // defensive, in case you further modify etnnpbf
let netnnpbf = etnnpbf / (etNNPitchBendRangeUp - etNNPitchBendRangeDown)
if netnnpbf >= -0.5, netnnpbf <= 0.5 {
let netnnpb = Int((netnnpbf + 0.5) * (pitchBendHigh - pitchBendLow) + pitchBendLow)
etNNDictionary[MIDINoteNumber(i)] = TuningTableETNN(nnAs12ETNN, netnnpb)
delta12ETDictionary[MIDINoteNumber(i)] = TuningTableDelta12ET(nnAs12ETNN, delta12ETpbf)
}
}
}
// Log("etnn dictionary:\(etNNDictionary)")
}
/// Renders and returns the masterSet values as an array of cents
public func masterSetInCents() -> [Cents] {
let cents = masterSet.map { log2($0) * 1_200 }
return cents
}
}
|
mit
|
47e0a47278dfa3130140bed5127e59e2
| 35.165354 | 116 | 0.615066 | 4.347373 | false | false | false | false |
hollance/swift-algorithm-club
|
Selection Sampling/SelectionSampling.playground/Contents.swift
|
3
|
1895
|
//: Playground - noun: a place where people can play
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
import Foundation
/* Returns a random integer in the range min...max, inclusive. */
public func random(min: Int, max: Int) -> Int {
assert(min < max)
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
/*
func select<T>(from a: [T], count k: Int) -> [T] {
var a = a
for i in 0..<k {
let r = random(min: i, max: a.count - 1)
if i != r {
swap(&a[i], &a[r])
}
}
return Array(a[0..<k])
}
*/
func select<T>(from a: [T], count requested: Int) -> [T] {
var examined = 0
var selected = 0
var b = [T]()
while selected < requested {
// Calculate random variable 0.0 <= r < 1.0 (exclusive!).
let r = Double(arc4random()) / 0x100000000
let leftToExamine = a.count - examined
let leftToAdd = requested - selected
// Decide whether to use the next record from the input.
if Double(leftToExamine) * r < Double(leftToAdd) {
selected += 1
b.append(a[examined])
}
examined += 1
}
return b
}
let poem = [
"there", "once", "was", "a", "man", "from", "nantucket",
"who", "kept", "all", "of", "his", "cash", "in", "a", "bucket",
"his", "daughter", "named", "nan",
"ran", "off", "with", "a", "man",
"and", "as", "for", "the", "bucket", "nan", "took", "it",
]
let output = select(from: poem, count: 10)
print(output)
output.count
// Use this to verify that all input elements have the same probability
// of being chosen. The "counts" dictionary should have a roughly equal
// count for each input element.
/*
let input = [ "a", "b", "c", "d", "e", "f", "g" ]
var counts = [String: Int]()
for x in input {
counts[x] = 0
}
for _ in 0...1000 {
let output = select(from: input, count: 3)
for x in output {
counts[x] = counts[x]! + 1
}
}
print(counts)
*/
|
mit
|
7d6493d1eacd7628ecd65e94d171e7a2
| 21.831325 | 71 | 0.582586 | 2.933437 | false | false | false | false |
hollance/swift-algorithm-club
|
Red-Black Tree/RedBlackTree.swift
|
2
|
24739
|
//Copyright (c) 2016 Matthijs Hollemans and contributors
//
//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
private enum RBTreeColor {
case red
case black
}
private enum RotationDirection {
case left
case right
}
// MARK: - RBNode
public class RBTreeNode<T: Comparable>: Equatable {
public typealias RBNode = RBTreeNode<T>
fileprivate var color: RBTreeColor = .black
fileprivate var key: T?
var leftChild: RBNode?
var rightChild: RBNode?
fileprivate weak var parent: RBNode?
public init(key: T?, leftChild: RBNode?, rightChild: RBNode?, parent: RBNode?) {
self.key = key
self.leftChild = leftChild
self.rightChild = rightChild
self.parent = parent
self.leftChild?.parent = self
self.rightChild?.parent = self
}
public convenience init(key: T?) {
self.init(key: key, leftChild: RBNode(), rightChild: RBNode(), parent: RBNode())
}
// For initialising the nullLeaf
public convenience init() {
self.init(key: nil, leftChild: nil, rightChild: nil, parent: nil)
self.color = .black
}
var isRoot: Bool {
return parent == nil
}
var isLeaf: Bool {
return rightChild == nil && leftChild == nil
}
var isNullLeaf: Bool {
return key == nil && isLeaf && color == .black
}
var isLeftChild: Bool {
return parent?.leftChild === self
}
var isRightChild: Bool {
return parent?.rightChild === self
}
var grandparent: RBNode? {
return parent?.parent
}
var sibling: RBNode? {
if isLeftChild {
return parent?.rightChild
} else {
return parent?.leftChild
}
}
var uncle: RBNode? {
return parent?.sibling
}
}
// MARK: - RedBlackTree
public class RedBlackTree<T: Comparable> {
public typealias RBNode = RBTreeNode<T>
fileprivate(set) var root: RBNode
fileprivate(set) var size = 0
fileprivate let nullLeaf = RBNode()
fileprivate let allowDuplicateNode: Bool
public init(_ allowDuplicateNode: Bool = false) {
root = nullLeaf
self.allowDuplicateNode = allowDuplicateNode
}
}
// MARK: - Size
extension RedBlackTree {
public func count() -> Int {
return size
}
public func isEmpty() -> Bool {
return size == 0
}
public func allElements() -> [T] {
var nodes: [T] = []
getAllElements(node: root, nodes: &nodes)
return nodes
}
private func getAllElements(node: RBTreeNode<T>, nodes: inout [T]) {
guard !node.isNullLeaf else {
return
}
if let left = node.leftChild {
getAllElements(node: left, nodes: &nodes)
}
if let key = node.key {
nodes.append(key)
}
if let right = node.rightChild {
getAllElements(node: right, nodes: &nodes)
}
}
}
// MARK: - Equatable protocol
extension RBTreeNode {
static public func == <T>(lhs: RBTreeNode<T>, rhs: RBTreeNode<T>) -> Bool {
return lhs.key == rhs.key
}
}
// MARK: - Finding a nodes successor
extension RBTreeNode {
/*
* Returns the inorder successor node of a node
* The successor is a node with the next larger key value of the current node
*/
public func getSuccessor() -> RBNode? {
// If node has right child: successor min of this right tree
if let rightChild = self.rightChild {
if !rightChild.isNullLeaf {
return rightChild.minimum()
}
}
// Else go upward until node left child
var currentNode = self
var parent = currentNode.parent
while currentNode.isRightChild {
if let parent = parent {
currentNode = parent
}
parent = currentNode.parent
}
return parent
}
}
// MARK: - Searching
extension RBTreeNode {
/*
* Returns the node with the minimum key of the current subtree
*/
public func minimum() -> RBNode? {
if let leftChild = leftChild {
if !leftChild.isNullLeaf {
return leftChild.minimum()
}
return self
}
return self
}
/*
* Returns the node with the maximum key of the current subtree
*/
public func maximum() -> RBNode? {
if let rightChild = rightChild {
if !rightChild.isNullLeaf {
return rightChild.maximum()
}
return self
}
return self
}
}
extension RedBlackTree {
/*
* Returns the node with the given key |input| if existing
*/
public func search(input: T) -> RBNode? {
return search(key: input, node: root)
}
/*
* Returns the node with given |key| in subtree of |node|
*/
fileprivate func search(key: T, node: RBNode?) -> RBNode? {
// If node nil -> key not found
guard let node = node else {
return nil
}
// If node is nullLeaf == semantically same as if nil
if !node.isNullLeaf {
if let nodeKey = node.key {
// Node found
if key == nodeKey {
return node
} else if key < nodeKey {
return search(key: key, node: node.leftChild)
} else {
return search(key: key, node: node.rightChild)
}
}
}
return nil
}
}
// MARK: - Finding maximum and minimum value
extension RedBlackTree {
/*
* Returns the minimum key value of the whole tree
*/
public func minValue() -> T? {
guard let minNode = root.minimum() else {
return nil
}
return minNode.key
}
/*
* Returns the maximum key value of the whole tree
*/
public func maxValue() -> T? {
guard let maxNode = root.maximum() else {
return nil
}
return maxNode.key
}
}
// MARK: - Inserting new nodes
extension RedBlackTree {
/*
* Insert a node with key |key| into the tree
* 1. Perform normal insert operation as in a binary search tree
* 2. Fix red-black properties
* Runntime: O(log n)
*/
public func insert(key: T) {
// If key must be unique and find the key already existed, quit
if search(input: key) != nil && !allowDuplicateNode {
return
}
if root.isNullLeaf {
root = RBNode(key: key)
} else {
insert(input: RBNode(key: key), node: root)
}
size += 1
}
/*
* Nearly identical insert operation as in a binary search tree
* Differences: All nil pointers are replaced by the nullLeaf, we color the inserted node red,
* after inserting we call insertFixup to maintain the red-black properties
*/
private func insert(input: RBNode, node: RBNode) {
guard let inputKey = input.key, let nodeKey = node.key else {
return
}
if inputKey < nodeKey {
guard let child = node.leftChild else {
addAsLeftChild(child: input, parent: node)
return
}
if child.isNullLeaf {
addAsLeftChild(child: input, parent: node)
} else {
insert(input: input, node: child)
}
} else {
guard let child = node.rightChild else {
addAsRightChild(child: input, parent: node)
return
}
if child.isNullLeaf {
addAsRightChild(child: input, parent: node)
} else {
insert(input: input, node: child)
}
}
}
private func addAsLeftChild(child: RBNode, parent: RBNode) {
parent.leftChild = child
child.parent = parent
child.color = .red
insertFixup(node: child)
}
private func addAsRightChild(child: RBNode, parent: RBNode) {
parent.rightChild = child
child.parent = parent
child.color = .red
insertFixup(node: child)
}
/*
* Fixes possible violations of the red-black property after insertion
* Only violation of red-black properties occurs at inserted node |z| and z.parent
* We have 3 distinct cases: case 1, 2a and 2b
* - case 1: may repeat, but only h/2 steps, where h is the height of the tree
* - case 2a -> case 2b -> red-black tree
* - case 2b -> red-black tree
*/
private func insertFixup(node z: RBNode) {
if !z.isNullLeaf {
guard let parentZ = z.parent else {
return
}
// If both |z| and his parent are red -> violation of red-black property -> need to fix it
if parentZ.color == .red {
guard let uncle = z.uncle else {
return
}
// Case 1: Uncle red -> recolor + move z
if uncle.color == .red {
parentZ.color = .black
uncle.color = .black
if let grandparentZ = parentZ.parent {
grandparentZ.color = .red
// Move z to grandparent and check again
insertFixup(node: grandparentZ)
}
}
// Case 2: Uncle black
else {
var zNew = z
// Case 2.a: z right child -> rotate
if parentZ.isLeftChild && z.isRightChild {
zNew = parentZ
leftRotate(node: zNew)
} else if parentZ.isRightChild && z.isLeftChild {
zNew = parentZ
rightRotate(node: zNew)
}
// Case 2.b: z left child -> recolor + rotate
zNew.parent?.color = .black
if let grandparentZnew = zNew.grandparent {
grandparentZnew.color = .red
if z.isLeftChild {
rightRotate(node: grandparentZnew)
} else {
leftRotate(node: grandparentZnew)
}
// We have a valid red-black-tree
}
}
}
}
root.color = .black
}
}
// MARK: - Deleting a node
extension RedBlackTree {
/*
* Delete a node with key |key| from the tree
* 1. Perform standard delete operation as in a binary search tree
* 2. Fix red-black properties
* Runntime: O(log n)
*/
public func delete(key: T) {
if size == 1 {
root = nullLeaf
size -= 1
} else if let node = search(key: key, node: root) {
if !node.isNullLeaf {
delete(node: node)
size -= 1
}
}
}
/*
* Nearly identical delete operation as in a binary search tree
* Differences: All nil pointers are replaced by the nullLeaf,
* after deleting we call insertFixup to maintain the red-black properties if the delted node was
* black (as if it was red -> no violation of red-black properties)
*/
private func delete(node z: RBNode) {
var nodeY = RBNode()
var nodeX = RBNode()
if let leftChild = z.leftChild, let rightChild = z.rightChild {
if leftChild.isNullLeaf || rightChild.isNullLeaf {
nodeY = z
} else {
if let successor = z.getSuccessor() {
nodeY = successor
}
}
}
if let leftChild = nodeY.leftChild {
if !leftChild.isNullLeaf {
nodeX = leftChild
} else if let rightChild = nodeY.rightChild {
nodeX = rightChild
}
}
nodeX.parent = nodeY.parent
if let parentY = nodeY.parent {
// Should never be the case, as parent of root = nil
if parentY.isNullLeaf {
root = nodeX
} else {
if nodeY.isLeftChild {
parentY.leftChild = nodeX
} else {
parentY.rightChild = nodeX
}
}
} else {
root = nodeX
}
if nodeY != z {
z.key = nodeY.key
}
// If sliced out node was red -> nothing to do as red-black-property holds
// If it was black -> fix red-black-property
if nodeY.color == .black {
deleteFixup(node: nodeX)
}
}
/*
* Fixes possible violations of the red-black property after deletion
* We have w distinct cases: only case 2 may repeat, but only h many steps, where h is the height
* of the tree
* - case 1 -> case 2 -> red-black tree
* case 1 -> case 3 -> case 4 -> red-black tree
* case 1 -> case 4 -> red-black tree
* - case 3 -> case 4 -> red-black tree
* - case 4 -> red-black tree
*/
private func deleteFixup(node x: RBNode) {
var xTmp = x
if !x.isRoot && x.color == .black {
guard var sibling = x.sibling else {
return
}
// Case 1: Sibling of x is red
if sibling.color == .red {
// Recolor
sibling.color = .black
if let parentX = x.parent {
parentX.color = .red
// Rotation
if x.isLeftChild {
leftRotate(node: parentX)
} else {
rightRotate(node: parentX)
}
// Update sibling
if let sibl = x.sibling {
sibling = sibl
}
}
}
// Case 2: Sibling is black with two black children
if sibling.leftChild?.color == .black && sibling.rightChild?.color == .black {
// Recolor
sibling.color = .red
// Move fake black unit upwards
if let parentX = x.parent {
deleteFixup(node: parentX)
}
// We have a valid red-black-tree
} else {
// Case 3: a. Sibling black with one black child to the right
if x.isLeftChild && sibling.rightChild?.color == .black {
// Recolor
sibling.leftChild?.color = .black
sibling.color = .red
// Rotate
rightRotate(node: sibling)
// Update sibling of x
if let sibl = x.sibling {
sibling = sibl
}
}
// Still case 3: b. One black child to the left
else if x.isRightChild && sibling.leftChild?.color == .black {
// Recolor
sibling.rightChild?.color = .black
sibling.color = .red
// Rotate
leftRotate(node: sibling)
// Update sibling of x
if let sibl = x.sibling {
sibling = sibl
}
}
// Case 4: Sibling is black with red right child
// Recolor
if let parentX = x.parent {
sibling.color = parentX.color
parentX.color = .black
// a. x left and sibling with red right child
if x.isLeftChild {
sibling.rightChild?.color = .black
// Rotate
leftRotate(node: parentX)
}
// b. x right and sibling with red left child
else {
sibling.leftChild?.color = .black
//Rotate
rightRotate(node: parentX)
}
// We have a valid red-black-tree
xTmp = root
}
}
}
xTmp.color = .black
}
}
// MARK: - Rotation
extension RedBlackTree {
/*
* Left rotation around node x
* Assumes that x.rightChild y is not a nullLeaf, rotates around the link from x to y,
* makes y the new root of the subtree with x as y's left child and y's left child as x's right
* child, where n = a node, [n] = a subtree
* | |
* x y
* / \ ~> / \
* [A] y x [C]
* / \ / \
* [B] [C] [A] [B]
*/
fileprivate func leftRotate(node x: RBNode) {
rotate(node: x, direction: .left)
}
/*
* Right rotation around node y
* Assumes that y.leftChild x is not a nullLeaf, rotates around the link from y to x,
* makes x the new root of the subtree with y as x's right child and x's right child as y's left
* child, where n = a node, [n] = a subtree
* | |
* x y
* / \ <~ / \
* [A] y x [C]
* / \ / \
* [B] [C] [A] [B]
*/
fileprivate func rightRotate(node x: RBNode) {
rotate(node: x, direction: .right)
}
/*
* Rotation around a node x
* Is a local operation preserving the binary-search-tree property that only exchanges pointers.
* Runntime: O(1)
*/
private func rotate(node x: RBNode, direction: RotationDirection) {
var nodeY: RBNode? = RBNode()
// Set |nodeY| and turn |nodeY|'s left/right subtree into |x|'s right/left subtree
switch direction {
case .left:
nodeY = x.rightChild
x.rightChild = nodeY?.leftChild
x.rightChild?.parent = x
case .right:
nodeY = x.leftChild
x.leftChild = nodeY?.rightChild
x.leftChild?.parent = x
}
// Link |x|'s parent to nodeY
nodeY?.parent = x.parent
if x.isRoot {
if let node = nodeY {
root = node
}
} else if x.isLeftChild {
x.parent?.leftChild = nodeY
} else if x.isRightChild {
x.parent?.rightChild = nodeY
}
// Put |x| on |nodeY|'s left
switch direction {
case .left:
nodeY?.leftChild = x
case .right:
nodeY?.rightChild = x
}
x.parent = nodeY
}
}
// MARK: - Verify
extension RedBlackTree {
/*
* Verifies that the existing tree fulfills all red-black properties
* Returns true if the tree is a valid red-black tree, false otherwise
*/
public func verify() -> Bool {
if root.isNullLeaf {
print("The tree is empty")
return true
}
return property2() && property4() && property5()
}
// Property 1: Every node is either red or black -> fullfilled through setting node.color of type
// RBTreeColor
// Property 2: The root is black
private func property2() -> Bool {
if root.color == .red {
print("Property-Error: Root is red")
return false
}
return true
}
// Property 3: Every nullLeaf is black -> fullfilled through initialising nullLeafs with color = black
// Property 4: If a node is red, then both its children are black
private func property4() -> Bool {
return property4(node: root)
}
private func property4(node: RBNode) -> Bool {
if node.isNullLeaf {
return true
}
if let leftChild = node.leftChild, let rightChild = node.rightChild {
if node.color == .red {
if !leftChild.isNullLeaf && leftChild.color == .red {
print("Property-Error: Red node with key \(String(describing: node.key)) has red left child")
return false
}
if !rightChild.isNullLeaf && rightChild.color == .red {
print("Property-Error: Red node with key \(String(describing: node.key)) has red right child")
return false
}
}
return property4(node: leftChild) && property4(node: rightChild)
}
return false
}
// Property 5: For each node, all paths from the node to descendant leaves contain the same number
// of black nodes (same blackheight)
private func property5() -> Bool {
if property5(node: root) == -1 {
return false
} else {
return true
}
}
private func property5(node: RBNode) -> Int {
if node.isNullLeaf {
return 0
}
guard let leftChild = node.leftChild, let rightChild = node.rightChild else {
return -1
}
let left = property5(node: leftChild)
let right = property5(node: rightChild)
if left == -1 || right == -1 {
return -1
} else if left == right {
let addedHeight = node.color == .black ? 1 : 0
return left + addedHeight
} else {
print("Property-Error: Black height violated at node with key \(String(describing: node.key))")
return -1
}
}
}
// MARK: - Debugging
extension RBTreeNode: CustomDebugStringConvertible {
public var debugDescription: String {
var s = ""
if isNullLeaf {
s = "nullLeaf"
} else {
if let key = key {
s = "key: \(key)"
} else {
s = "key: nil"
}
if let parent = parent {
s += ", parent: \(String(describing: parent.key))"
}
if let left = leftChild {
s += ", left = [" + left.debugDescription + "]"
}
if let right = rightChild {
s += ", right = [" + right.debugDescription + "]"
}
s += ", color = \(color)"
}
return s
}
}
extension RedBlackTree: CustomDebugStringConvertible {
public var debugDescription: String {
return root.debugDescription
}
}
extension RBTreeNode: CustomStringConvertible {
public var description: String {
var s = ""
if isNullLeaf {
s += "nullLeaf"
} else {
if let left = leftChild {
s += "(\(left.description)) <- "
}
if let key = key {
s += "\(key)"
} else {
s += "nil"
}
s += ", \(color)"
if let right = rightChild {
s += " -> (\(right.description))"
}
}
return s
}
}
extension RedBlackTree: CustomStringConvertible {
public var description: String {
if root.isNullLeaf {
return "[]"
} else {
return root.description
}
}
}
|
mit
|
67e239a54f3d1cd757db7f2b921a3cc8
| 30.118239 | 114 | 0.506366 | 4.621521 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS
|
App_VolksWagenFinal-/App_VolksWagenFinal-/VWDetalleConcesionarioViewController.swift
|
1
|
3080
|
//
// VWDetalleConcesionarioViewController.swift
// App_VolksWagenFinal_CICE
//
// Created by Formador on 3/10/16.
// Copyright © 2016 icologic. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class VWDetalleConcesionarioViewController: UIViewController {
//MARK: - VARIABLES LOCALES GLOBALES
var arrayConcesionariosData : VWConcesionariosModel?
let CONSTANTES = Constantes()
//MARK: - IBOUTLET
@IBOutlet weak var myImagenConcesionarioDetalle: UIImageView!
@IBOutlet weak var myNombreConcesionarioDetalle: UILabel!
@IBOutlet weak var myTelefonoFijoConcesionarioDetalle: UILabel!
@IBOutlet weak var myProvinciaConcesionarioDetalle: UILabel!
@IBOutlet weak var myContactoConcesionarioDetalle: UILabel!
@IBOutlet weak var myEmailConcesionarioDetalle: UILabel!
@IBOutlet weak var myDireccionConcesionarioDetalle: UILabel!
@IBOutlet weak var myMapaLocalizacionConcesionarioDetalle: MKMapView!
@IBOutlet weak var myScrollViewConcesionarioDetalle: UIScrollView!
//MARK: - IBACTION
override func viewDidLoad() {
super.viewDidLoad()
//Setter de las propiedades
myScrollViewConcesionarioDetalle.contentSize = CGSizeMake(320, 768)
myNombreConcesionarioDetalle.text = arrayConcesionariosData?.Nombre
myTelefonoFijoConcesionarioDetalle.text = String(arrayConcesionariosData?.telefono)
myProvinciaConcesionarioDetalle.text = arrayConcesionariosData?.Provincia_Nombre
myContactoConcesionarioDetalle.text = arrayConcesionariosData?.Contacto
myEmailConcesionarioDetalle.text = arrayConcesionariosData?.CoreoContacto
myDireccionConcesionarioDetalle.text = arrayConcesionariosData?.Ubicacion
//Setter de la Imagen
let myImagenConcesionario = arrayConcesionariosData?.Imagen
let myImagenUrl = NSURL(string: getImagePath(myImagenConcesionario!))
let myImageData = NSData(contentsOfURL: myImagenUrl!)
myImagenConcesionarioDetalle.image = UIImage(data: myImageData!)
//Setter de Mapa
let region = MKCoordinateRegion(center: CLLocationCoordinate2DMake((arrayConcesionariosData?.Latitud!)!, (arrayConcesionariosData?.Longitud!)!), span: MKCoordinateSpanMake(0.01, 0.01))
myMapaLocalizacionConcesionarioDetalle.setRegion(region, animated: true)
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake((arrayConcesionariosData?.Latitud!)!, (arrayConcesionariosData?.Longitud!)!)
annotation.title = arrayConcesionariosData?.Ubicacion
annotation.subtitle = arrayConcesionariosData?.Provincia_Nombre
myMapaLocalizacionConcesionarioDetalle.addAnnotation(annotation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getImagePath(nombreImagen : String) ->String {
return CONSTANTES.BASE_FOTO_URL + nombreImagen
}
}
|
apache-2.0
|
78baa11038452ad6fda008661be66e82
| 41.178082 | 193 | 0.745697 | 3.887626 | false | false | false | false |
Erin-Mounts/BridgeAppSDK
|
BridgeAppSDK/ProfileViewController.swift
|
1
|
7289
|
/*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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.
*/
import UIKit
import ResearchKit
import HealthKit
public class ProfileViewController: UITableViewController, HealthClientType {
// MARK: Properties
let healthObjectTypes = [
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!
]
var healthStore: HKHealthStore?
@IBOutlet var applicationNameLabel: UILabel!
// MARK: UIViewController
override public func viewDidLoad() {
super.viewDidLoad()
guard let healthStore = healthStore else { fatalError("healhStore not set") }
// Ensure the table view automatically sizes its rows.
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
// Request authrization to query the health objects that need to be shown.
let typesToRequest = Set<HKObjectType>(healthObjectTypes)
healthStore.requestAuthorizationToShareTypes(nil, readTypes: typesToRequest) { authorized, error in
guard authorized else { return }
// Reload the table view cells on the main thread.
NSOperationQueue.mainQueue().addOperationWithBlock() {
let allRowIndexPaths = self.healthObjectTypes.enumerate().map { NSIndexPath(forRow: $0.index, inSection: 0) }
self.tableView.reloadRowsAtIndexPaths(allRowIndexPaths, withRowAnimation: .Automatic)
}
}
}
// MARK: UITableViewDataSource
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return healthObjectTypes.count
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCellWithIdentifier(ProfileStaticTableViewCell.reuseIdentifier, forIndexPath: indexPath) as? ProfileStaticTableViewCell else { fatalError("Unable to dequeue a ProfileStaticTableViewCell") }
let objectType = healthObjectTypes[indexPath.row]
switch(objectType.identifier) {
case HKCharacteristicTypeIdentifierDateOfBirth:
configureCellWithDateOfBirth(cell)
case HKQuantityTypeIdentifierHeight:
let title = NSLocalizedString("Height", comment: "")
configureCell(cell, withTitleText: title, valueForQuantityTypeIdentifier: objectType.identifier)
case HKQuantityTypeIdentifierBodyMass:
let title = NSLocalizedString("Weight", comment: "")
configureCell(cell, withTitleText: title, valueForQuantityTypeIdentifier: objectType.identifier)
default:
fatalError("Unexpected health object type identifier - \(objectType.identifier)")
}
return cell
}
override public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: Cell configuration
func configureCellWithDateOfBirth(cell: ProfileStaticTableViewCell) {
// Set the default cell content.
cell.titleLabel.text = NSLocalizedString("Date of Birth", comment: "")
cell.valueLabel.text = NSLocalizedString("-", comment: "")
// Update the value label with the date of birth from the health store.
guard let healthStore = healthStore else { return }
do {
let dateOfBirth = try healthStore.dateOfBirth()
let now = NSDate()
let ageComponents = NSCalendar.currentCalendar().components(.Year, fromDate: dateOfBirth, toDate: now, options: .WrapComponents)
let age = ageComponents.year
cell.valueLabel.text = "\(age)"
}
catch {
}
}
func configureCell(cell: ProfileStaticTableViewCell, withTitleText titleText: String, valueForQuantityTypeIdentifier identifier: String) {
// Set the default cell content.
cell.titleLabel.text = titleText
cell.valueLabel.text = NSLocalizedString("-", comment: "")
/*
Check a health store has been set and a `HKQuantityType` can be
created with the identifier provided.
*/
guard let healthStore = healthStore, quantityType = HKQuantityType.quantityTypeForIdentifier(identifier) else { return }
// Get the most recent entry from the health store.
healthStore.mostRecentQauntitySampleOfType(quantityType) { quantity, _ in
guard let quantity = quantity else { return }
// Update the cell on the main thread.
NSOperationQueue.mainQueue().addOperationWithBlock() {
guard let indexPath = self.indexPathForObjectTypeIdentifier(identifier) else { return }
guard let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? ProfileStaticTableViewCell else { return }
cell.valueLabel.text = "\(quantity)"
}
}
}
// MARK: Convenience
func indexPathForObjectTypeIdentifier(identifier: String) -> NSIndexPath? {
for (index, objectType) in healthObjectTypes.enumerate() where objectType.identifier == identifier {
return NSIndexPath(forRow: index, inSection: 0)
}
return nil
}
}
|
bsd-3-clause
|
4d2a0f199461e4084247990bcc7b5452
| 43.993827 | 238 | 0.698175 | 5.887722 | false | false | false | false |
yangchenghu/actor-platform
|
actor-apps/app-ios/ActorSwift/Strings.swift
|
2
|
3809
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
extension String {
var length: Int { return self.characters.count }
func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet());
}
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
func first(count: Int) -> String {
let realCount = min(count, length);
return substringToIndex(startIndex.advancedBy(realCount));
}
func strip(set: NSCharacterSet) -> String {
return componentsSeparatedByCharactersInSet(set).joinWithSeparator("")
}
func replace(src: String, dest:String) -> String {
return stringByReplacingOccurrencesOfString(src, withString: dest, options: NSStringCompareOptions(), range: nil)
}
func toLong() -> Int64? {
return NSNumberFormatter().numberFromString(self)?.longLongValue
}
func toJLong() -> jlong {
return jlong(toLong()!)
}
func smallValue() -> String {
let trimmed = trim();
if (trimmed.isEmpty){
return "#";
}
let letters = NSCharacterSet.letterCharacterSet()
let res: String = self[0];
if (res.rangeOfCharacterFromSet(letters) != nil) {
return res.uppercaseString;
} else {
return "#";
}
}
func hasPrefixInWords(prefix: String) -> Bool {
var components = self.componentsSeparatedByString(" ")
for i in 0..<components.count {
if components[i].lowercaseString.hasPrefix(prefix.lowercaseString) {
return true
}
}
return false
}
func contains(text: String) -> Bool {
return self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil
}
func rangesOfString(text: String) -> [Range<String.Index>] {
var res = [Range<String.Index>]()
var searchRange = Range<String.Index>(start: self.startIndex, end: self.endIndex)
while true {
let found = self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
if found != nil {
res.append(found!)
searchRange = Range<String.Index>(start: found!.endIndex, end: self.endIndex)
} else {
break
}
}
return res
}
func repeatString(count: Int) -> String {
var res = ""
for _ in 0..<count {
res += self
}
return res
}
var asNS: NSString { return (self as NSString) }
}
extension NSAttributedString {
func append(text: NSAttributedString) -> NSAttributedString {
let res = NSMutableAttributedString()
res.appendAttributedString(self)
res.appendAttributedString(text)
return res
}
func append(text: String, font: UIFont) -> NSAttributedString {
return append(NSAttributedString(string: text, attributes: [NSFontAttributeName: font]))
}
convenience init(string: String, font: UIFont) {
self.init(string: string, attributes: [NSFontAttributeName: font])
}
}
extension NSMutableAttributedString {
func appendFont(font: UIFont) {
self.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, self.length))
}
func appendColor(color: UIColor) {
self.addAttribute(NSForegroundColorAttributeName, value: color.CGColor, range: NSMakeRange(0, self.length))
}
}
|
mit
|
8b0acad160904fef32d6efa6759a93cf
| 28.527132 | 136 | 0.601995 | 4.902188 | false | false | false | false |
yangchenghu/actor-platform
|
actor-apps/app-ios/ActorCore/Providers/Storage/FMDBIndex.swift
|
11
|
4238
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
@objc class FMDBIndex: NSObject, ARIndexStorage {
var db :FMDatabase? = nil
var isTableChecked: Bool = false
let databasePath: String
let tableName: String
let queryCreate: String
let queryCreateIndex: String
let queryAdd: String
let queryItem: String
let queryFind: String
let queryDelete: String
let queryDeleteValue: String
let queryDeleteAll: String
let queryCount: String
init(databasePath: String, tableName: String) {
self.databasePath = databasePath
self.tableName = tableName;
self.queryCreate = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + //
"\"ID\" INTEGER NOT NULL," + // 0: id
"\"VALUE\" INTEGER NOT NULL," + // 1: value
"PRIMARY KEY(\"ID\"));";
self.queryCreateIndex = "CREATE INDEX IF NOT EXISTS IDX_ID_VALUE ON " + tableName + " (\"VALUE\");"
self.queryAdd = "REPLACE INTO " + tableName + " (\"ID\",\"VALUE\") VALUES (?,?)";
self.queryItem = "SELECT \"VALUE\" FROM " + tableName + " WHERE \"ID\" = ?;";
self.queryFind = "SElECT \"ID\" FROM " + tableName + " WHERE \"VALUE\" <= ?;"
self.queryDelete = "DELETE FROM " + tableName + " WHERE \"ID\" = ?;"
self.queryDeleteAll = "DELETE FROM " + tableName + ";"
self.queryDeleteValue = "DELETE FROM " + tableName + " WHERE \"VALUE\" <= ?;"
self.queryCount = "SELECT COUNT(*) FROM " + tableName + ";"
}
func checkTable() {
if (isTableChecked) {
return
}
isTableChecked = true;
self.db = FMDatabase(path: databasePath)
self.db!.open()
if (!db!.tableExists(tableName)) {
db!.executeUpdate(queryCreate)
db!.executeUpdate(queryCreateIndex)
}
}
func putWithKey(key: jlong, withValue value: jlong) {
checkTable()
db!.beginTransaction()
db!.executeUpdate(queryAdd, key.toNSNumber(), value.toNSNumber())
db!.commit()
}
func get(key: jlong) -> JavaLangLong! {
checkTable()
// TODO: Fix?
let result = db!.longForQuery(queryItem, key.toNSNumber());
if (result == nil) {
return nil
}
return JavaLangLong(long: jlong(result))
}
func findBeforeValue(value: jlong) -> JavaUtilList! {
checkTable()
let dbResult = db!.executeQuery(queryFind, value.toNSNumber())
if dbResult == nil {
return JavaUtilArrayList()
}
let res = JavaUtilArrayList()
while(dbResult!.next()) {
res.addWithId(JavaLangLong(long: jlong(dbResult!.longLongIntForColumn("ID"))))
}
dbResult!.close()
return res
}
func removeBeforeValue(value: jlong) -> JavaUtilList! {
checkTable()
let res = findBeforeValue(value)
removeWithKeys(res)
return res
}
func removeWithKey(key: jlong) {
checkTable()
db!.beginTransaction()
db!.executeUpdate(queryDelete, key.toNSNumber())
db!.commit()
}
func removeWithKeys(keys: JavaUtilList!) {
checkTable()
db!.beginTransaction()
for index in 0..<keys.size() {
let key = (keys.getWithInt(index) as! JavaLangLong).longLongValue()
db!.executeUpdate(queryDelete, key.toNSNumber())
}
db!.commit()
}
func getCount() -> jint {
checkTable()
let result = db!.executeQuery(queryCount)
if (result == nil) {
return 0;
}
if (result!.next()) {
let res = jint(result!.intForColumnIndex(0))
result?.close()
return res
} else {
result?.close()
}
return 0;
}
func clear() {
checkTable()
db!.beginTransaction()
db!.executeUpdate(queryDeleteAll);
db!.commit()
}
}
|
mit
|
a29b09eb390c9b98b99780f139fc5984
| 26.525974 | 107 | 0.530675 | 4.693245 | false | false | false | false |
jasperscholten/programmeerproject
|
JasperScholten-project/RegisterEmployeeVC.swift
|
1
|
7799
|
//
// RegisterEmployeeVC.swift
// JasperScholten-project
//
// Created by Jasper Scholten on 18-01-17.
// Copyright © 2017 Jasper Scholten. All rights reserved.
//
// This ViewController deals with registering new users, that want to sign up to an existing organisation. Organisations and there locations are shown through a pickerView.
import UIKit
import Firebase
class RegisterEmployeeVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
// MARK: Constants and variables
let userRef = FIRDatabase.database().reference(withPath: "Users")
let organisationRef = FIRDatabase.database().reference(withPath: "Organisations")
let locationsRef = FIRDatabase.database().reference(withPath: "Locations")
var organisation = ["Geen organisatie"]
var organisationID = ["Geen locaties"]
var location = [String: [String]]()
// MARK: - Outlets
@IBOutlet weak var name: UITextField!
@IBOutlet weak var mail: UITextField!
@IBOutlet weak var employeeNr: UITextField!
@IBOutlet weak var organisationPicker: UIPickerView!
@IBOutlet weak var locationPicker: UIPickerView!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var repeatPassword: UITextField!
// MARK: - UIViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
keyboardActions()
// Retrieve organisations from Firebase
organisationRef.observe(.value, with: { snapshot in
var newOrganisations: [String] = []
var newOrganisationIDs: [String] = []
for item in snapshot.children {
let organisationData = Organisation(snapshot: item as! FIRDataSnapshot)
newOrganisations.append(organisationData.organisation)
newOrganisationIDs.append(organisationData.organisationID)
}
self.organisation = newOrganisations
self.organisationID = newOrganisationIDs
self.organisationPicker.reloadAllComponents()
})
// Retrieve locations from Firebase
locationsRef.observe(.value, with: { snapshot in
let snapshotValue = snapshot.value as! [String: [String: String]]
var newLocations: [String: [String]] = [:]
for (key, value) in snapshotValue {
var locations: [String] = []
for newLocation in value {
locations.append(newLocation.value)
}
newLocations[key] = locations
}
self.location = newLocations
self.locationPicker.reloadAllComponents()
})
}
// Lock current view on Portrait mode. [1, 2]
override var shouldAutorotate: Bool { return false }
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
// MARK: - Picker views [3]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == organisationPicker {
return organisation.count
} else {
let pickedOrganisation = organisationID[organisationPicker.selectedRow(inComponent: 0)]
return (location[pickedOrganisation] ?? ["Geen organisaties geladen"]).count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == organisationPicker {
return organisation[row]
} else {
let pickedOrganisation = organisationID[organisationPicker.selectedRow(inComponent: 0)]
let pickedLocations = location[pickedOrganisation]
return pickedLocations?[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.organisationPicker.reloadAllComponents()
self.locationPicker.reloadAllComponents()
}
// MARK: - Actions
@IBAction func registerUser(_ sender: Any) {
if password.text! != repeatPassword.text! {
alertSingleOption(titleInput: "Wachtwoorden komen niet overeen", messageInput: "")
password.text! = ""
repeatPassword.text! = ""
} else if name.text!.isEmpty || mail.text!.isEmpty || employeeNr.text!.isEmpty {
alertSingleOption(titleInput: "Vul alle velden in",
messageInput: "Vul alle velden in om een organisatie te kunnen registreren.")
} else {
createUser()
}
}
@IBAction func cancelRegistration(_ sender: Any) {
self.dismiss(animated: true, completion: {})
}
// MARK: - Functions
func createUser() {
FIRAuth.auth()!.createUser(withEmail: mail.text!, password: password.text!) { user, error in
if error == nil {
let pickedOrganisation = self.organisation[self.organisationPicker.selectedRow(inComponent: 0)]
let pickedOrganisationID = self.organisationID[self.organisationPicker.selectedRow(inComponent: 0)]
let pickedLocations = self.location[pickedOrganisationID]
let pickedLocation = pickedLocations![self.locationPicker.selectedRow(inComponent: 0)]
let user = User(uid: (user?.uid)!,
email: self.mail.text!,
name: self.name.text!,
admin: false,
employeeNr: self.employeeNr.text!,
organisationName: pickedOrganisation,
organisationID: pickedOrganisationID,
locationID: pickedLocation,
accepted: false)
let newUserRef = self.userRef.child(user.uid)
newUserRef.setValue(user.toAnyObject())
self.dismiss(animated: true, completion: {})
} else {
self.alertSingleOption(titleInput: "Foute invoer",
messageInput: "Het emailadres of wachtwoord dat je hebt ingevoerd bestaat al of voldoet niet aan de eisen. Een wachtwoord moet bestaan uit minmaal 6 karakters.")
}
}
}
// Handle keyboard behaviour.
func keyboardActions() {
// Make sure all buttons and inputfields keep visible when the keyboard appears. [4]
NotificationCenter.default.addObserver(self, selector: #selector(RegisterEmployeeVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RegisterEmployeeVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// Enable user to dismiss keyboard by tapping outside of it. [5]
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RegisterEmployeeVC.dismissKeyboard))
view.addGestureRecognizer(tap)
}
}
// MARK: - References
// 1. http://stackoverflow.com/questions/25651969/setting-device-orientation-in-swift-ios
// 2. http://stackoverflow.com/questions/38721302/shouldautorotate-function-in-xcode-8-beta-4
// 3. http://stackoverflow.com/questions/30238224/multiple-uipickerview-in-the-same-uiview
// 4. http://stackoverflow.com/questions/26070242/move-view-with-keyboard-using-swift
// 5. http://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift
|
apache-2.0
|
6b630d093092745e30e9fc96eabc19c1
| 43.306818 | 200 | 0.634906 | 4.992318 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
TranslationEditor/USXAttributes.swift
|
1
|
2366
|
//
// USXAttributes.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 29.9.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// the value of a charStyle attribute should be a CharStyle
let CharStyleAttributeName = NSAttributedStringKey("charStyle")
// IsNoteAttribute is used for marking areas in string that contain note data
// The value should be a boolean determining whether this area should be considered to be a note (no attribute is considered false)
let IsNoteAttributeName = NSAttributedStringKey("isNote")
// NoteMarkerAttribute value determines whether the marker is considered to be a start (true) or end (false) of a note
let NoteMarkerAttributeName = NSAttributedStringKey("noteMarker")
// the value of a verseIndexMarker attribute should be the verse index as an integer
let VerseIndexMarkerAttributeName = NSAttributedStringKey("verseIndexMarker")
// Para marker and para style have the para style as values
let ParaMarkerAttributeName = NSAttributedStringKey("paraMarker")
let ParaStyleAttributeName = NSAttributedStringKey("paraStyle")
// The value of this attribute should be the chapter index
let ChapterMarkerAttributeName = NSAttributedStringKey("chapterMarker")
let chapterMarkerFont = UIFont(name: "Arial", size: 32.0)!
let defaultParagraphFont = UIFont(name: "Arial", size: 16.0)!
let headingFont = UIFont(name: "Arial", size: 24.0)!
let quotationFont = defaultParagraphFont.withItalic ?? defaultParagraphFont
let notesFont = UIFont(name: "Arial", size: 12.0)!
enum ParagraphStyling
{
case rightAlignment
case indented(level: Int)
case centered
case thin
case list(level: Int)
// COMPUTED PROPERTIES ----------
var style: NSParagraphStyle
{
let style = NSMutableParagraphStyle()
let indentStep: CGFloat = 32
switch self
{
case .rightAlignment: style.alignment = .right
case .indented(let level):
style.firstLineHeadIndent = indentStep * CGFloat(level)
style.headIndent = indentStep * CGFloat(level)
case .centered: style.alignment = .center
case .thin:
style.firstLineHeadIndent = indentStep
style.headIndent = indentStep
style.tailIndent = indentStep
case .list(let level):
let firstIndent = indentStep * CGFloat(level)
style.firstLineHeadIndent = firstIndent
style.headIndent = firstIndent + indentStep
}
return style
}
}
|
mit
|
376d482c0e61315ab4c111f0848c3a28
| 31.847222 | 131 | 0.764482 | 4.178445 | false | false | false | false |
phatblat/Butler
|
Tests/ButlerTests/MavenModuleSetSpec.swift
|
1
|
3889
|
//
// MavenModuleSetSpec.swift
// ButlerTests
//
// Created by Ben Chatelain on 6/18/17.
//
@testable import Butler
import Quick
import Nimble
import Foundation
class MavenModuleSetSpec: QuickSpec {
override func spec() {
describe("maven module set") {
let jsonFile: NSString = "MavenModuleSet.json"
var job: MavenModuleSet! = nil
beforeEach {
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: jsonFile.deletingPathExtension,
withExtension: jsonFile.pathExtension,
subdirectory: "JSON/Job")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
job = try! decoder.decode(MavenModuleSet.self, from: data)
}
it("has class") {
expect(job._class) == JavaClass.mavenModuleSet
}
it("has actions") {
expect(job.actions.count) == 4
}
it("is buildable") {
expect(job.buildable) == true
}
it("has no builds") {
expect(job.builds.count) == 0
}
it("has color") {
expect(job.color) == "notbuilt"
}
it("is not concurrent") {
expect(job.concurrentBuild) == false
}
it("has an empty description") {
expect(job.description) == ""
}
it("has a display name") {
expect(job.displayName) == "Maven"
}
it("has no display name or null") {
expect(job.displayNameOrNull).to(beNil())
}
it("has no downstream projects") {
expect(job.downstreamProjects.count) == 0
}
it("has no first build") {
expect(job.firstBuild).to(beNil())
}
it("has a full display name") {
expect(job.fullDisplayName) == "Job Types » Maven"
}
it("has a full name") {
expect(job.fullName) == "Job Types/Maven"
}
it("has no health reports") {
expect(job.healthReport.count) == 0
}
it("is not in queue") {
expect(job.inQueue) == false
}
it("does not keep dependencies") {
expect(job.keepDependencies) == false
}
it("has no last builds") {
expect(job.lastBuild).to(beNil())
expect(job.lastCompletedBuild).to(beNil())
expect(job.lastFailedBuild).to(beNil())
expect(job.lastStableBuild).to(beNil())
expect(job.lastSuccessfulBuild).to(beNil())
expect(job.lastUnstableBuild).to(beNil())
expect(job.lastUnsuccessfulBuild).to(beNil())
}
it("has no modules") {
expect(job.modules.count) == 0
}
it("has a name") {
expect(job.name) == "Maven"
}
it("has a next build number") {
expect(job.nextBuildNumber) == 1
}
it("has no properties") {
expect(job.property.count) == 0
}
it("has no queue item") {
expect(job.queueItem).to(beNil())
}
it("has no scm") {
expect(job.scm["_class"]) == JavaClass.nullScm
}
it("has no upstream projects") {
expect(job.upstreamProjects.count) == 0
}
it("has a url") {
expect(job.url.absoluteString) == "http://jenkins.log-g.co/job/Job%20Types/job/Maven/"
}
}
}
}
|
mit
|
ad57b10cee050fdaf10515152e869e5f
| 33.714286 | 102 | 0.463992 | 4.552693 | false | false | false | false |
CharlesVu/Smart-iPad
|
Persistance/Persistance/Persistance.swift
|
1
|
2253
|
//
// Persistance.swift
// Persistance
//
// Created by Charles Vu on 05/06/2019.
// Copyright © 2019 Charles Vu. All rights reserved.
//
import RealmSwift
import os.log
protocol Migrating {
var schemaVersion: UInt64 { get }
func migrate(from oldSchemaVersion: UInt64, with migration: RealmSwift.Migration)
}
public class Persistance {
public static var shared = Persistance()
lazy var realm: Realm = createRealm()
private init() { }
private static func localDocumentPath(for fileName: String) -> URL {
let fileManager = FileManager.default
let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
return url.appendingPathComponent(fileName)
}
static internal func reduceMigrationBlock(migrators: [Migrating]) -> MigrationBlock {
let migrationBlock: RealmSwift.MigrationBlock = { migration, oldSchemaVersion in
// migration stuff can go here!
migrators.sorted { $0.schemaVersion < $1.schemaVersion }.forEach {
if oldSchemaVersion < $0.schemaVersion {
$0.migrate(from: oldSchemaVersion, with: migration)
}
}
}
return migrationBlock
}
static private func realmConfiguration(migrationBlock: MigrationBlock) -> Realm.Configuration {
var configuration = Realm.Configuration()
configuration.fileURL = localDocumentPath(for: "default.realm")
os_log("💙 Realm Location: %@", configuration.fileURL!.absoluteString)
configuration.schemaVersion = Version.current
return configuration
}
private func createRealm() -> Realm! {
let migrations = Persistance.reduceMigrationBlock(migrators: Migrations.allMigrations())
return try! Realm(configuration: Persistance.realmConfiguration(migrationBlock: migrations))
}
internal func userPreferences() -> RealmUserPreferences {
guard let preferences = realm.objects(RealmUserPreferences.self).first else {
let newPreferences = RealmUserPreferences()
try! realm.write {
realm.add(newPreferences)
}
return newPreferences
}
return preferences
}
}
|
mit
|
cc530e7c00f5be777fec367807f82e06
| 33.075758 | 100 | 0.665629 | 5.03132 | false | true | false | false |
LittoCats/IOSDevelopExtension
|
CommonTool/FoundationExtension.swift
|
1
|
33276
|
//
// FoundationExtension.swift
// CommonTool
//
// Created by 程巍巍 on 3/16/15.
// Copyright (c) 2015 Littocats. All rights reserved.
//
import Foundation
import JavaScriptCore
/****************************************************** NSDate ***************************************************************/
extension NSDate {
/**
* NSDate 与字符串的格式化转换
e.g. 2014-10-19 23:58:59:345
yyyy : 2014 //年
YYYY ; 2014 //年
MM : 10 //年中的月份 1〜12
dd : 19 //当月中的第几天 1〜31
DD : 292 //当年中的第几天 1〜366
hh : 11 //当天中的小时 12 进制 1〜12
HH : 23 //当天中的小时 24 进制 0 〜 23
mm : 58 //当前小时中的分钟 0 〜 59
ss : 59 //当前分钟中的秒数 0 〜 59
SSS : 345 //当前秒中的耗秒数 0 〜 999
a : PM //表示上下午 AM 上午 PM 下午
A : 86339345 //当天中已经过的耗秒数
t : //普通字符无意义,通常用作日期与时间的分隔
T : //普通字符无意义,通常用作日期与时间的分隔
v : China Time //时间名
V : cnsha //时间名缩写
w : 43 //当年中的第几周 星期天为周的开始
W : 4 //当月中的第几周 星期天为周的开始
F : 3 //当月中的第几周 星期一为周的开始
x : +08 //表示当前时区
x : +08 //表示当前时区
*/
convenience init?(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0){
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = formatter.dateFromString("\(year)-\(month)-\(day) \(hour):\(minute):\(second)")
if date == nil {self.init();return nil}
self.init(timeIntervalSince1970: date!.timeIntervalSince1970)
}
convenience init?(lunarYear year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0, isLeapMonth: Bool = false){
var lunar = LunarComponent(lunarYear: year, month: month, day: day, hour: hour, minute: minute, second: second, isLeapMonth: isLeapMonth)
if lunar == nil {self.init(); return nil}
self.init(timeIntervalSince1970: lunar!.interval)
self.lunar = lunar!
}
var week: Int{
var days = Int((self.timeIntervalSince1970 - NSDate(year: 1900, month: 1, day: 1)!.timeIntervalSince1970) / 86400)
return days % 7 + 1
}
var lunar: LunarComponent{
get{
var components = objc_getAssociatedObject(self, &LunarComponent.Lib.LunarComponentKey) as? LunarComponent
if components == nil {
components = LunarComponent(date: self)
self.lunar = components!
}
return components!
}set{
objc_setAssociatedObject(self, &LunarComponent.Lib.LunarComponentKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
}
extension NSDate {
final class LunarComponent {
var components = (
Hour:0,
Minute: 0,
Second: 0,
SolarYear: 0,
SolarMonth:0,
SolarDay:0,
LunarYear: 0,
LunarMonth: 0,
LunarDay: 0,
LunarYearCN: "",
LunarMonthCN: "",
LunarDayCN: "",
GZHour: "", // 时
GZQuarter: "", // 刻
GZYear: "",
GZMonth: "",
GZDay: "",
AnimalSymbol: 0, // 1 ~ 12
AnimalSymbolCN: "",
AstronomySymbol: 0, // 1 ~ 12
AstronomySymbolCN: "",
SolarTerm: 0, // 0 ~ 23
SolarTermCN: "",
Week: 0,
isSolarTerm: false,
isToday: false,
isLeapMonth: false
)
private var interval: NSTimeInterval! //timeIntervalSince1970
// 农历年、月、日初始化
init?(lunarYear year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0, isLeapMonth: Bool = false){
let ymd = year * 10000 + month * 100 + day
if ymd > 21001201 || ymd < 19000131 {return nil}
if (hour < 0 || hour >= 24) || (minute < 0 || minute >= 60) || (second < 0 || second >= 60) {
return nil
}
// 时晨
components.GZHour = "\(LunarComponent.Lib.Zhi[hour/2])时"
var quarter = minute/15
if quarter > 0{
components.GZQuarter = "\(LunarComponent.Lib.nStr1[quarter])刻"
}
var leapOffset = 0
var leapMonth = LunarComponent.leapMonthOfYear(year)
if isLeapMonth && leapMonth != month {return nil}
// 验正天是否超也范围
var d = LunarComponent.daysOfLunarMonth(month, inYear: year)
if d < day {return nil}
// 计算农历的时间差
var offset = 0
for i in 1900..<year {
offset += LunarComponent.daysOfLunarYear(i)
}
var isAdd = false
var daysOfLeapMonth = LunarComponent.daysOfLeapMonthInYear(year)
for i in 1..<month{
if !isAdd && (leapMonth <= i && leapMonth > 0){
offset += daysOfLeapMonth
isAdd = true
}
offset += LunarComponent.daysOfLunarMonth(i, inYear: year)
}
// 转换闰月农历 需补充该年闰月的前一个月的时差
if isLeapMonth {offset += d}
// 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点)
// NSTimeZone.localTimeZone().secondsFromGMT 为时区修正
let stmap = (offset + day - 31) * 86400 - 2203804800 + hour * 3600 + minute * 60 + second - NSTimeZone.localTimeZone().secondsFromGMT
self.interval = NSTimeInterval(stmap)
if !parseComponents() {return nil}
}
// 农历年、月、日初始化
private init?(date: NSDate){
self.interval = date.timeIntervalSince1970
if !parseComponents() {return nil}
}
private func parseComponents() ->Bool{
let date = NSDate(timeIntervalSince1970: self.interval)
components.Hour = LunarComponent.component(date: date, symbol: "HH")
components.Minute = LunarComponent.component(date: date, symbol: "mm")
components.Second = LunarComponent.component(date: date, symbol: "ss")
components.SolarYear = LunarComponent.component(date: date, symbol: "yyyy")
components.SolarMonth = LunarComponent.component(date: date, symbol: "MM")
components.SolarDay = LunarComponent.component(date: date, symbol: "dd")
let ymd = components.SolarYear * 10000 + components.SolarMonth * 100 + components.SolarDay
if ymd > 21001201 || ymd < 19000131 {return false}
var objDate = NSDate(year: components.SolarYear, month: components.SolarMonth - 1, day: components.SolarDay)
var leap = 0
var temp = 0
// 修正 y m d 参数
var y = LunarComponent.component(date: objDate!, symbol: "yyyy")
var m = LunarComponent.component(date: objDate!, symbol: "MM") + 1
var d = LunarComponent.component(date: objDate!, symbol: "dd")
var offset = Int((NSDate(year: y, month: m, day: d)!.timeIntervalSince1970 - NSDate(year: 1900, month: 1, day: 31)!.timeIntervalSince1970)/86400)
var i = 0
for (i = 1900; i < 2100; i++) {
if offset <= 0 {break}
temp = LunarComponent.daysOfLunarYear(i)
offset -= temp
}
if offset < 0 { offset += temp; i--}
// isToday
var today = NSDate()
components.isToday = LunarComponent.component(date: today, symbol: "yyyy") == y && LunarComponent.component(date: today, symbol: "MM") == m && LunarComponent.component(date: today, symbol: "dd") == d
// week
components.Week = Int((date.timeIntervalSince1970 - NSDate(year: 1900, month: 1, day: 1)!.timeIntervalSince1970) / 86400) % 7 + 1
// 农历年
components.LunarYear = i
components.LunarYearCN = LunarComponent.cnNameOfYear(i)
// 计算闰月
leap = LunarComponent.leapMonthOfYear(i)
components.isLeapMonth = false
for (i = 1; i < 12; i++){
if offset <= 0 {break}
// 闰月
if leap > 0 && i == leap+1 && components.isLeapMonth == false {
--i
components.isLeapMonth = true
temp = LunarComponent.daysOfLeapMonthInYear(y) // 计算闰月天数
}else{
temp = LunarComponent.daysOfLunarMonth(i, inYear: y)
}
// 解除闰月
if components.isLeapMonth && i == leap + 1{
components.isLeapMonth = false
}
offset -= temp
}
if offset == 0 && leap > 0 && i == leap + 1 {
if components.isLeapMonth {
components.isLeapMonth = false
}else{
components.isLeapMonth = true
--i
}
}
if offset < 0 {
offset += temp
--i
}
// 农历月
components.LunarMonth = i
components.LunarMonthCN = LunarComponent.cnNameOfMonth(i)
// 农历日
components.LunarDay = offset + 1
components.LunarDayCN = LunarComponent.cnNameOfDay(offset+1)
// 天干地支处理
var sm = m-1
var term3 = LunarComponent.solarTermOfYear(y, serialNo: 3) // 该农历年立春日期
var gzY = LunarComponent.toGanZhi(y - 4) // 普通按年份计算,下方尚需按立春节气来修正
// 依据立春日进行修正gzY
if sm < 2 && d < term3 {
gzY = LunarComponent.toGanZhi(y - 5)
}else{
gzY = LunarComponent.toGanZhi(y - 4)
}
components.GZYear = gzY
// 月柱 1900年1月小寒以前为 丙子月(60进制12)
var firstNode = LunarComponent.solarTermOfYear(y, serialNo: m*2-1) // 返回当月「节」为几日开始
var secondNode = LunarComponent.solarTermOfYear(y, serialNo: m*2) // 返回当月「节」为几日开始
// 依据12节气修正干支月
if d < firstNode {
components.GZMonth = LunarComponent.toGanZhi((y-1900)*12+m+11)
}else{
components.GZMonth = LunarComponent.toGanZhi((y-1900)*12+m+12)
}
// 日柱 当月一日与 1900/1/1 相差天数
var dayCyclical = Int(NSDate(year: y, month: sm, day: 1)!.timeIntervalSince1970/86400) + 25567 + 10 + 29
components.GZDay = LunarComponent.toGanZhi(dayCyclical+d-1)
// 判断是否是节气
if firstNode == d {
components.isSolarTerm = true
components.SolarTerm = m*2-2
}
if secondNode == d {
components.isSolarTerm = true
components.SolarTerm = m*2-1
}
if components.isSolarTerm {
components.SolarTermCN = LunarComponent.Lib.SolarTerm[components.SolarTerm]
}
// 属相
components.AnimalSymbol = LunarComponent.animalSymbolOfYear(components.LunarYear)
components.AnimalSymbolCN = LunarComponent.Lib.Animals[components.AnimalSymbol]
// 星座
components.AstronomySymbol = LunarComponent.astronomyOfMonth(m, day: y)
components.AstronomySymbolCN = LunarComponent.Lib.AstronomyName[components.AstronomySymbol]
return true
}
private struct Lib {
static var LunarComponentKey = "LunarComponentKey"
static let LunarInfo = [ //农历1900-2100的润大小信息表
0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2,
0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977,
0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970,
0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950,
0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557,
0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0,
0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0,
0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6,
0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570,
0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0,
0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5,
0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930,
0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530,
0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45,
0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0,
0x14b63,0x09370,0x049f8,0x04970,0x064b0,0x168a6,0x0ea50,0x06b20,0x1a6c4,0x0aae0,
0x0a2e0,0x0d2e3,0x0c960,0x0d557,0x0d4a0,0x0da50,0x05d55,0x056a0,0x0a6d0,0x055d4,
0x052d0,0x0a9b8,0x0a950,0x0b4a0,0x0b6a6,0x0ad50,0x055a0,0x0aba4,0x0a5b0,0x052b0,
0x0b273,0x06930,0x07337,0x06aa0,0x0ad50,0x14b55,0x04b60,0x0a570,0x054e4,0x0d160,
0x0e968,0x0d520,0x0daa0,0x16aa6,0x056d0,0x04ae0,0x0a9d4,0x0a2d0,0x0d150,0x0f252,
0x0d520
]
// 公历每个月份的天数普通表
private static let SolarMonth = [0,31,28,31,30,31,30,31,31,30,31,30,31]
// 天干地支之天干速查表
private static let Gan = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
// 天干地支之地支速查表
private static let Zhi = ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"]
// 天干地支之地支速查表<=>生肖
private static let Animals = ["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
// 24节气速查表
private static let SolarTerm = ["小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"]
// 十二星座速查表
private static let AstronomyInfo = [23, 21, 20, 21, 21, 22, 22, 24, 24, 24, 24, 23, 23]
private static let AstronomyName = ["摩羯座", "水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"]
// 1900-2100各年的24节气日期速查表
// 数字转中文速查表
private static let nStr1 = ["〇","一","二","三","四","五","六","七","八","九","十"]
// 日期转农历称呼速查表
private static let nStr2 = ["初","十","廿","卅"]
// 月份转农历称呼速查表
private static let nStr3 = ["正","二","三","四","五","六","七","八","九","十","冬","腊"]
// 1900-2100各年的24节气日期速查表
private static let sTermInfo: [NSString] = [
"9778397bd097c36b0b6fc9274c91aa","97b6b97bd19801ec9210c965cc920e","97bcf97c3598082c95f8c965cc920f",
"97bd0b06bdb0722c965ce1cfcc920f","b027097bd097c36b0b6fc9274c91aa","97b6b97bd19801ec9210c965cc920e",
"97bcf97c359801ec95f8c965cc920f","97bd0b06bdb0722c965ce1cfcc920f","b027097bd097c36b0b6fc9274c91aa",
"97b6b97bd19801ec9210c965cc920e","97bcf97c359801ec95f8c965cc920f","97bd0b06bdb0722c965ce1cfcc920f",
"b027097bd097c36b0b6fc9274c91aa","9778397bd19801ec9210c965cc920e","97b6b97bd19801ec95f8c965cc920f",
"97bd09801d98082c95f8e1cfcc920f","97bd097bd097c36b0b6fc9210c8dc2","9778397bd197c36c9210c9274c91aa",
"97b6b97bd19801ec95f8c965cc920e","97bd09801d98082c95f8e1cfcc920f","97bd097bd097c36b0b6fc9210c8dc2",
"9778397bd097c36c9210c9274c91aa","97b6b97bd19801ec95f8c965cc920e","97bcf97c3598082c95f8e1cfcc920f",
"97bd097bd097c36b0b6fc9210c8dc2","9778397bd097c36c9210c9274c91aa","97b6b97bd19801ec9210c965cc920e",
"97bcf97c3598082c95f8c965cc920f","97bd097bd097c35b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa",
"97b6b97bd19801ec9210c965cc920e","97bcf97c3598082c95f8c965cc920f","97bd097bd097c35b0b6fc920fb0722",
"9778397bd097c36b0b6fc9274c91aa","97b6b97bd19801ec9210c965cc920e","97bcf97c359801ec95f8c965cc920f",
"97bd097bd097c35b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa","97b6b97bd19801ec9210c965cc920e",
"97bcf97c359801ec95f8c965cc920f","97bd097bd097c35b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa",
"97b6b97bd19801ec9210c965cc920e","97bcf97c359801ec95f8c965cc920f","97bd097bd07f595b0b6fc920fb0722",
"9778397bd097c36b0b6fc9210c8dc2","9778397bd19801ec9210c9274c920e","97b6b97bd19801ec95f8c965cc920f",
"97bd07f5307f595b0b0bc920fb0722","7f0e397bd097c36b0b6fc9210c8dc2","9778397bd097c36c9210c9274c920e",
"97b6b97bd19801ec95f8c965cc920f","97bd07f5307f595b0b0bc920fb0722","7f0e397bd097c36b0b6fc9210c8dc2",
"9778397bd097c36c9210c9274c91aa","97b6b97bd19801ec9210c965cc920e","97bd07f1487f595b0b0bc920fb0722",
"7f0e397bd097c36b0b6fc9210c8dc2","9778397bd097c36b0b6fc9274c91aa","97b6b97bd19801ec9210c965cc920e",
"97bcf7f1487f595b0b0bb0b6fb0722","7f0e397bd097c35b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa",
"97b6b97bd19801ec9210c965cc920e","97bcf7f1487f595b0b0bb0b6fb0722","7f0e397bd097c35b0b6fc920fb0722",
"9778397bd097c36b0b6fc9274c91aa","97b6b97bd19801ec9210c965cc920e","97bcf7f1487f531b0b0bb0b6fb0722",
"7f0e397bd097c35b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa","97b6b97bd19801ec9210c965cc920e",
"97bcf7f1487f531b0b0bb0b6fb0722","7f0e397bd07f595b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa",
"97b6b97bd19801ec9210c9274c920e","97bcf7f0e47f531b0b0bb0b6fb0722","7f0e397bd07f595b0b0bc920fb0722",
"9778397bd097c36b0b6fc9210c91aa","97b6b97bd197c36c9210c9274c920e","97bcf7f0e47f531b0b0bb0b6fb0722",
"7f0e397bd07f595b0b0bc920fb0722","9778397bd097c36b0b6fc9210c8dc2","9778397bd097c36c9210c9274c920e",
"97b6b7f0e47f531b0723b0b6fb0722","7f0e37f5307f595b0b0bc920fb0722","7f0e397bd097c36b0b6fc9210c8dc2",
"9778397bd097c36b0b70c9274c91aa","97b6b7f0e47f531b0723b0b6fb0721","7f0e37f1487f595b0b0bb0b6fb0722",
"7f0e397bd097c35b0b6fc9210c8dc2","9778397bd097c36b0b6fc9274c91aa","97b6b7f0e47f531b0723b0b6fb0721",
"7f0e27f1487f595b0b0bb0b6fb0722","7f0e397bd097c35b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa",
"97b6b7f0e47f531b0723b0b6fb0721","7f0e27f1487f531b0b0bb0b6fb0722","7f0e397bd097c35b0b6fc920fb0722",
"9778397bd097c36b0b6fc9274c91aa","97b6b7f0e47f531b0723b0b6fb0721","7f0e27f1487f531b0b0bb0b6fb0722",
"7f0e397bd097c35b0b6fc920fb0722","9778397bd097c36b0b6fc9274c91aa","97b6b7f0e47f531b0723b0b6fb0721",
"7f0e27f1487f531b0b0bb0b6fb0722","7f0e397bd07f595b0b0bc920fb0722","9778397bd097c36b0b6fc9274c91aa",
"97b6b7f0e47f531b0723b0787b0721","7f0e27f0e47f531b0b0bb0b6fb0722","7f0e397bd07f595b0b0bc920fb0722",
"9778397bd097c36b0b6fc9210c91aa","97b6b7f0e47f149b0723b0787b0721","7f0e27f0e47f531b0723b0b6fb0722",
"7f0e397bd07f595b0b0bc920fb0722","9778397bd097c36b0b6fc9210c8dc2","977837f0e37f149b0723b0787b0721",
"7f07e7f0e47f531b0723b0b6fb0722","7f0e37f5307f595b0b0bc920fb0722","7f0e397bd097c35b0b6fc9210c8dc2",
"977837f0e37f14998082b0787b0721","7f07e7f0e47f531b0723b0b6fb0721","7f0e37f1487f595b0b0bb0b6fb0722",
"7f0e397bd097c35b0b6fc9210c8dc2","977837f0e37f14998082b0787b06bd","7f07e7f0e47f531b0723b0b6fb0721",
"7f0e27f1487f531b0b0bb0b6fb0722","7f0e397bd097c35b0b6fc920fb0722","977837f0e37f14998082b0787b06bd",
"7f07e7f0e47f531b0723b0b6fb0721","7f0e27f1487f531b0b0bb0b6fb0722","7f0e397bd097c35b0b6fc920fb0722",
"977837f0e37f14998082b0787b06bd","7f07e7f0e47f531b0723b0b6fb0721","7f0e27f1487f531b0b0bb0b6fb0722",
"7f0e397bd07f595b0b0bc920fb0722","977837f0e37f14998082b0787b06bd","7f07e7f0e47f531b0723b0b6fb0721",
"7f0e27f1487f531b0b0bb0b6fb0722","7f0e397bd07f595b0b0bc920fb0722","977837f0e37f14998082b0787b06bd",
"7f07e7f0e47f149b0723b0787b0721","7f0e27f0e47f531b0b0bb0b6fb0722","7f0e397bd07f595b0b0bc920fb0722",
"977837f0e37f14998082b0723b06bd","7f07e7f0e37f149b0723b0787b0721","7f0e27f0e47f531b0723b0b6fb0722",
"7f0e397bd07f595b0b0bc920fb0722","977837f0e37f14898082b0723b02d5","7ec967f0e37f14998082b0787b0721",
"7f07e7f0e47f531b0723b0b6fb0722","7f0e37f1487f595b0b0bb0b6fb0722","7f0e37f0e37f14898082b0723b02d5",
"7ec967f0e37f14998082b0787b0721","7f07e7f0e47f531b0723b0b6fb0722","7f0e37f1487f531b0b0bb0b6fb0722",
"7f0e37f0e37f14898082b0723b02d5","7ec967f0e37f14998082b0787b06bd","7f07e7f0e47f531b0723b0b6fb0721",
"7f0e37f1487f531b0b0bb0b6fb0722","7f0e37f0e37f14898082b072297c35","7ec967f0e37f14998082b0787b06bd",
"7f07e7f0e47f531b0723b0b6fb0721","7f0e27f1487f531b0b0bb0b6fb0722","7f0e37f0e37f14898082b072297c35",
"7ec967f0e37f14998082b0787b06bd","7f07e7f0e47f531b0723b0b6fb0721","7f0e27f1487f531b0b0bb0b6fb0722",
"7f0e37f0e366aa89801eb072297c35","7ec967f0e37f14998082b0787b06bd","7f07e7f0e47f149b0723b0787b0721",
"7f0e27f1487f531b0b0bb0b6fb0722","7f0e37f0e366aa89801eb072297c35","7ec967f0e37f14998082b0723b06bd",
"7f07e7f0e47f149b0723b0787b0721","7f0e27f0e47f531b0723b0b6fb0722","7f0e37f0e366aa89801eb072297c35",
"7ec967f0e37f14998082b0723b06bd","7f07e7f0e37f14998083b0787b0721","7f0e27f0e47f531b0723b0b6fb0722",
"7f0e37f0e366aa89801eb072297c35","7ec967f0e37f14898082b0723b02d5","7f07e7f0e37f14998082b0787b0721",
"7f07e7f0e47f531b0723b0b6fb0722","7f0e36665b66aa89801e9808297c35","665f67f0e37f14898082b0723b02d5",
"7ec967f0e37f14998082b0787b0721","7f07e7f0e47f531b0723b0b6fb0722","7f0e36665b66a449801e9808297c35",
"665f67f0e37f14898082b0723b02d5","7ec967f0e37f14998082b0787b06bd","7f07e7f0e47f531b0723b0b6fb0721",
"7f0e36665b66a449801e9808297c35","665f67f0e37f14898082b072297c35","7ec967f0e37f14998082b0787b06bd",
"7f07e7f0e47f531b0723b0b6fb0721","7f0e26665b66a449801e9808297c35","665f67f0e37f1489801eb072297c35",
"7ec967f0e37f14998082b0787b06bd","7f07e7f0e47f531b0723b0b6fb0721","7f0e27f1487f531b0b0bb0b6fb0722"
]
}
}
}
extension NSDate.LunarComponent{
// 返回农历y年闰月是哪个月;若y年没有闰月 则返回0
// param lunar Year
// return Number (0-12)
class func leapMonthOfYear(year: Int)-> Int{
return Lib.LunarInfo[year-1900] & 0xf
}
// 返回农历y年闰月的天数 若该年没有闰月则返回0
// param lunar Year
// return Number (0、29、30)
class func daysOfLeapMonthInYear(year: Int)-> Int{
if leapMonthOfYear(year) > 0{
if Bool(Lib.LunarInfo[year-1900] & 0x10000) {return 30}
else{return 29}
}
return 0
}
// 返回农历y年一整年的总天数
// param lunar Year
// return Number
class func daysOfLunarYear(year: Int)-> Int{
var sum = 348
var i = 0x8000
while i > 0x8{
if Bool(Lib.LunarInfo[year - 1900] & i) {sum += 1}
i >>= 1
}
return sum + daysOfLeapMonthInYear(year)
}
// 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapMonthDays方法
// param lunar Year
// return Number (-1、29、30)
class func daysOfLunarMonth(month: Int, inYear year: Int)->Int{
if month > 12 || month < 1 {return -1}
if Bool(Lib.LunarInfo[year - 1900] & (0x10000 >> month)){return 30}
else{return 29}
}
// 返回公历(!)y年m月的天数
// param solar Year
// return Number (-1、28、29、30、31)
class func daysOfMonth(month: Int, ofYear year: Int) ->Int{
if month > 12 || month < 1 {return -1}
if month != 2 {return Lib.SolarMonth[month]}
//2月份的闰平规律测算后确认返回28或29
if year%4 == 0 && year%100 != 0 || year%400 == 0 {return 29}
else{return 28}
}
// 传入offset偏移量返回干支
// param offset 相对甲子的偏移量
// return 中文
class func toGanZhi(offset: Int) ->String{
return Lib.Gan[offset%10]+Lib.Zhi[offset%12]
}
// 公历(!)y年获得该年第n个节气的公历日期
// param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起
// return day Number
class func solarTermOfYear(year: Int, serialNo: Int) ->Int{
if year < 1900 || year > 2100 || serialNo < 1 || serialNo > 24{return -1}
let no = serialNo - 1
var table:NSString = Lib.sTermInfo[year - 1900]
var info = NSString(format:"%i",parseInt(("0x" + table.substringWithRange(NSMakeRange(no/4*5, 5)))))
var index_location = [0, 1, 3, 4]
var index_length = [1, 2]
return parseInt(info.substringWithRange(NSMakeRange(index_location[no%4], index_length[no%4%2])))
}
// 传入农历数字年份返回汉语通俗表示法
// param lunar year
// return Cn string
// 若参数错误 返回 ""
class func cnNameOfYear(year: Int)->String{
var yStr: NSString = "\(year)"
var ret = ""
for i in 0..<(yStr as NSString).length {
ret += Lib.nStr1[parseInt(yStr.substringWithRange(NSMakeRange(i, 1)))]
}
return ret+"年"
}
// 传入农历数字月份返回汉语通俗表示法
// param lunar month
// return Cn string
// 若参数错误 返回 ""
class func cnNameOfMonth(month: Int)->String{
if month > 12 || month < 1 {return ""}
return Lib.nStr3[month - 1] + "月"
}
// 传入农历日期数字返回汉字表示法
// param lunar day
// return Cn string
// return Cn string
// eg: cnDay = toChinaDay 21 //cnMonth='廿一'
class func cnNameOfDay(day: Int) -> String{return Lib.nStr2[Int(day / 10)] + Lib.nStr1[day % 10]}
// 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春”
// param y year
// return Cn string
class func animalSymbolOfYear(year: Int) -> Int{return ( year - 4) % 12}
// 根据生日计算十二星座
// param solar month 1 ~ 12
// param solar day
// return Cn string
class func astronomyOfMonth(month: Int, day: Int) ->Int{
if day >= Lib.AstronomyInfo[month] {return month}
else{return month - 1}
}
private class func component(#date: NSDate, symbol: String) -> Int{
var formatter = NSDateFormatter()
formatter.dateFormat = symbol
return parseInt(formatter.stringFromDate(date))
}
private class func parseInt(string: String)-> Int{
struct IntSymbol {
static let HEX = ["0": 0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "a":10, "b":11, "c":12, "d":13, "e":14, "f":15]
}
let str: NSString = string.lowercaseString
var int: Int = 0
var symbol: NSString
var value: Int?
if str.hasPrefix("0x") {
var vstr: NSString = str.substringFromIndex(2)
for index in 0..<vstr.length {
symbol = vstr.substringWithRange(NSMakeRange(index, 1))
value = IntSymbol.HEX[symbol as String]
if value == nil {return 0}
int |= value! << (4 * (vstr.length - index - 1))
}
}else{
var vstr: NSString = str
for index in 0..<vstr.length {
symbol = vstr.substringWithRange(NSMakeRange(index, 1))
value = IntSymbol.HEX[symbol as String]
if value == nil {return 0}
int += value! * Int(pow(10, Float((vstr.length - index - 1))))
}
}
return int
}
}
/****************************************************** NSTimer ***************************************************************/
@objc protocol EasyTimer{
optional var userInfo: AnyObject? { get }
optional func invalidate()
optional func fire()
}
extension NSTimer: EasyTimer {
typealias NSTimerScheduledTask = (timer: EasyTimer)->Bool
// strict == false 时 task 永远在后台线程中执行
class func scheduled(#task:NSTimerScheduledTask, interval: NSTimeInterval, repeat: Bool = true, userInfo: AnyObject? = nil, strict: Bool = false) ->EasyTimer{
var timer: EasyTimer?
if strict {
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: NSScheduledTaskTimerTarget.self, selector: "reciveTimer:", userInfo: userInfo, repeats: repeat)
}else{
timer = EasyTimerTask(ti: interval, target: NSScheduledTaskTimerTarget.self, selector: "reciveTimer:", userInfo: userInfo, repeats: repeat)
}
objc_setAssociatedObject(timer, &NSScheduledTask.TaskKey, unsafeBitCast(task, AnyObject.self), objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return timer!
}
private struct NSScheduledTask {
static var TaskKey = "TaskKey"
}
@objc private class EasyTimerTask: EasyTimer {
var timeInterval: NSTimeInterval!
var userInfo: AnyObject?
var repeat: Bool
var valid: Bool = true
weak var target: AnyObject!
var selector: Selector!
init(ti: NSTimeInterval, target aTarget: AnyObject, selector aSelector: Selector, userInfo: AnyObject?, repeats yesOrNo: Bool){
self.timeInterval = ti
self.userInfo = userInfo
self.repeat = yesOrNo
self.target = aTarget
self.selector = aSelector
self.schedule()
}
func schedule(){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(self.timeInterval * 1000000000)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
if self.valid == false {return}
NSThread.detachNewThreadSelector(self.selector, toTarget: self, withObject: self)
if self.repeat {
self.schedule()
}
})
}
func invalidate(){
self.valid = false
}
func fire(){
NSThread.detachNewThreadSelector(self.selector, toTarget: self, withObject: self)
}
}
@objc private class NSScheduledTaskTimerTarget: NSObject{
@objc func reciveTimer(timer: NSTimer){
var taskObj: AnyObject? = objc_getAssociatedObject(timer, &NSScheduledTask.TaskKey)
if taskObj == nil { timer.invalidate(); return}
var task = unsafeBitCast(taskObj, NSTimerScheduledTask.self)
if task(timer: timer){
timer.invalidate()
}
}
}
}
|
apache-2.0
|
17254461512b4de787c87c6ad0b221ac
| 47.502326 | 211 | 0.598932 | 2.813562 | false | false | false | false |
tomburns/ios
|
FiveCalls/FiveCalls/ContactLog.swift
|
2
|
3367
|
//
// ContactLog.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/5/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
import Pantry
enum ContactOutcome : String {
case contacted
case voicemail = "vm"
case unavailable
// reserved for cases where we save something on disk that we later don't recognize
case unknown
}
struct ContactLog {
let issueId: String
let contactId: String
let phone: String
let outcome: ContactOutcome
let date: Date
static var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
}
extension ContactLog : Storable {
init(warehouse: Warehouseable) {
issueId = warehouse.get("issueId") ?? ""
contactId = warehouse.get("contactId") ?? ""
phone = warehouse.get("phone") ?? ""
outcome = warehouse.get("outcome").flatMap(ContactOutcome.init) ?? .unknown
date = ContactLog.dateFormatter.date(from: warehouse.get("date") ?? "") ?? Date()
}
func toDictionary() -> [String : Any] {
return [
"issueId": issueId,
"contactId": contactId,
"phone": phone,
"outcome": outcome.rawValue,
"date": ContactLog.dateFormatter.string(from: date)
]
}
}
extension ContactLog : Hashable {
var hashValue: Int {
return (issueId + contactId + phone + outcome.rawValue).hash
}
static func ==(lhs: ContactLog, rhs: ContactLog) -> Bool {
return lhs.issueId == rhs.issueId &&
lhs.contactId == rhs.contactId &&
lhs.phone == rhs.phone &&
lhs.outcome == rhs.outcome
}
}
struct ContactLogs {
private static let persistenceKey = "ContactLogs"
var all: [ContactLog]
init() {
all = []
}
private init(logs: [ContactLog]) {
all = logs
}
mutating func add(log: ContactLog) {
all.append(log)
save()
NotificationCenter.default.post(name: .callMade, object: log)
}
func save() {
Pantry.pack(all, key: ContactLogs.persistenceKey)
}
static func load() -> ContactLogs {
return Pantry.unpack(persistenceKey).flatMap(ContactLogs.init) ?? ContactLogs()
}
func methodOfContact(to contactId: String, forIssue issueId: String) -> ContactOutcome? {
return all.filter({$0.contactId == contactId && $0.issueId == issueId}).last?.outcome
}
func hasContacted(contactId: String, forIssue issueId: String) -> Bool {
guard let method = methodOfContact(to: contactId, forIssue: issueId) else {
return false
}
switch method {
case .contacted, .voicemail:
return true
case .unknown, .unavailable:
return false
}
}
func hasCompleted(issue: String, allContacts: [Contact]) -> Bool {
if (allContacts.count == 0) {
return false
}
for contact in allContacts {
if !hasContacted(contactId: contact.id, forIssue: issue) {
return false
}
}
return true
}
}
|
mit
|
874b6fb21390d27d3257fc7ba30f2a68
| 25.503937 | 93 | 0.579323 | 4.26616 | false | false | false | false |
amnuaym/TiAppBuilder
|
Day6/TestStaticTableView/TestStaticTableView/AppDelegate.swift
|
1
|
4607
|
//
// AppDelegate.swift
// TestStaticTableView
//
// Created by Amnuay M on 9/18/17.
// Copyright © 2017 Amnuay M. All rights reserved.
//
import UIKit
import CoreData
@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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "TestStaticTableView")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
gpl-3.0
|
189dab72f6779f9e4628097a2d8bee4a
| 48.526882 | 285 | 0.686713 | 5.860051 | false | false | false | false |
mozilla-mobile/firefox-ios
|
Shared/SystemUtils.swift
|
2
|
2494
|
// 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
/**
* System helper methods written in Swift.
*/
public struct SystemUtils {
/**
Returns an accurate version of the system uptime even while the device is asleep.
http://stackoverflow.com/questions/12488481/getting-ios-system-uptime-that-doesnt-pause-when-asleep
- returns: Time interval since last reboot.
*/
public static func systemUptime() -> TimeInterval {
var boottime = timeval()
var mib = [CTL_KERN, KERN_BOOTTIME]
var size = MemoryLayout<timeval>.stride
var now = time_t()
time(&now)
sysctl(&mib, u_int(mib.count), &boottime, &size, nil, 0)
let tv_sec: time_t = withUnsafePointer(to: &boottime.tv_sec) { $0.pointee }
return TimeInterval(now - tv_sec)
}
}
extension SystemUtils {
// This should be run on first run of the application.
// It shouldn't be run from an extension.
// Its function is to write a lock file that is only accessible from the application,
// and not accessible from extension when the device is locked. Thus, we can tell if an extension is being run
// when the device is locked.
public static func onFirstRun() {
guard let lockFileURL = lockedDeviceURL else { return }
let lockFile = lockFileURL.path
let fm = FileManager.default
if fm.fileExists(atPath: lockFile) {
return
}
let contents = "Device is unlocked".data(using: .utf8)
fm.createFile(atPath: lockFile, contents: contents, attributes: [FileAttributeKey(rawValue: FileAttributeKey.protectionKey.rawValue): FileProtectionType.complete])
}
private static var lockedDeviceURL: URL? {
let directoryURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppInfo.sharedContainerIdentifier)
return directoryURL?.appendingPathComponent("security.dummy")
}
public static func isDeviceLocked() -> Bool {
guard let lockFileURL = lockedDeviceURL else {
return true
}
do {
_ = try Data(contentsOf: lockFileURL, options: .mappedIfSafe)
return false
} catch let err as NSError {
return err.code == 257
} catch _ {
return true
}
}
}
|
mpl-2.0
|
33d17e308b6238545078aa1ba44a21cd
| 36.223881 | 171 | 0.65838 | 4.367776 | false | false | false | false |
eventtus/photo-editor
|
iOSPhotoEditor/UIImage+Size.swift
|
2
|
830
|
//
// UIImage+Size.swift
// Photo Editor
//
// Created by Mohamed Hamed on 5/2/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
public extension UIImage {
/**
Suitable size for specific height or width to keep same image ratio
*/
func suitableSize(heightLimit: CGFloat? = nil,
widthLimit: CGFloat? = nil )-> CGSize? {
if let height = heightLimit {
let width = (height / self.size.height) * self.size.width
return CGSize(width: width, height: height)
}
if let width = widthLimit {
let height = (width / self.size.width) * self.size.height
return CGSize(width: width, height: height)
}
return nil
}
}
|
mit
|
411d1cec153d3151646e366224f06b15
| 24.121212 | 72 | 0.541616 | 4.363158 | false | false | false | false |
mozilla-mobile/prox
|
Prox/Prox/Map View/MapViewController.swift
|
1
|
13110
|
/* 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 UIKit
import GoogleMaps
import SnapKit
private let fadeDuration: TimeInterval = 0.4
private let mapViewAnchorFromTop = mapViewMaskTopOffset - mapViewMaskMargin
/// If we use the search radius as the map mask diameter, the places are within the circle but the
/// markers overflow: this is padding to prevent the overflow.
private let mapViewPaddingForPins: CGFloat = 50
// Note: the constants are for inner circle. I haven't implemented see-through outer circle for time (yet?).
// The outer numbers are expanded by 30 in every direction (i.e. outside the view). 80% white
private let mapViewMaskMargin: CGFloat = 20
private let mapViewMaskTopOffset: CGFloat = 74
private let footerBottomOffset = Style.cardViewCornerRadius
private let footerCardMargin = 16
protocol MapViewControllerDelegate: class {
func mapViewController(_ mapViewController: MapViewController, didDismissWithSelectedPlace place: Place?)
}
enum MapState {
case initializing
case normal
case movingByCode
}
class MapViewController: UIViewController {
fileprivate let searchRadiusInMeters: Double = RemoteConfigKeys.searchRadiusInKm.value * 1000
weak var delegate: MapViewControllerDelegate?
weak var placesProvider: PlacesProvider?
weak var locationProvider: LocationProvider?
private let database = FirebasePlacesDatabase()
fileprivate var displayedPlaces: [Place]!
fileprivate var selectedPlace: Place?
fileprivate var selectedMarker: GMSMarker?
/// The filters the displayed list of places is filtered with.
fileprivate let enabledFilters: Set<PlaceFilter>
fileprivate var mapState = MapState.initializing
fileprivate var showMapConstraints = [Constraint]()
fileprivate var hideMapConstraints = [Constraint]()
private let mapViewMask = CAShapeLayer()
private lazy var mapView: GMSMapView = {
let camera = GMSCameraPosition.camera(withTarget: CLLocationCoordinate2D(latitude: 0, longitude: 0), zoom: 1.0) // initial position unused.
let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
mapView.isMyLocationEnabled = true
mapView.delegate = self
mapView.layer.mask = self.mapViewMask
return mapView
}()
fileprivate let searchButton: MapViewSearchButton = {
let button = MapViewSearchButton()
button.addTarget(self, action: #selector(searchInVisibleArea), for: .touchUpInside)
return button
}()
fileprivate var searchButtonTopConstraint: NSLayoutConstraint!
fileprivate lazy var placeFooter: MapViewCardFooter = {
let footer = MapViewCardFooter(bottomInset: footerBottomOffset)
footer.alpha = 0 // hide until the first place is selected.
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(closeWithSelected))
footer.addGestureRecognizer(tapRecognizer)
return footer
}()
init(selectedPlace: Place, enabledFilters: Set<PlaceFilter>) {
self.enabledFilters = enabledFilters
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = .overCurrentContext
self.transitioningDelegate = self
self.selectedPlace = selectedPlace
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented")
}
override func viewDidLoad() {
let closeButton = UIButton()
closeButton.setImage(#imageLiteral(resourceName: "button_dismiss"), for: .normal)
closeButton.addTarget(self, action: #selector(closeWithButton), for: .touchUpInside)
let container = UIView()
container.backgroundColor = Colors.mapViewBackgroundColor
for subview in [container, mapView, searchButton, placeFooter, closeButton] as [UIView] {
view.addSubview(subview)
}
container.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
showMapConstraints = [ make.top.bottom.equalToSuperview().constraint ]
hideMapConstraints = [ make.bottom.equalTo(view.snp.top).constraint ]
}
showMapConstraints.forEach { $0.deactivate() }
closeButton.snp.makeConstraints { make in
make.top.equalToSuperview().inset(45)
make.trailing.equalToSuperview().inset(27)
}
mapView.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
make.top.equalTo(container).inset(mapViewAnchorFromTop)
make.bottom.equalTo(placeFooter.snp.top)
}
searchButtonTopConstraint = searchButton.centerYAnchor.constraint(equalTo: mapView.topAnchor)
searchButtonTopConstraint.isActive = true
searchButton.snp.makeConstraints { make in
make.centerX.equalToSuperview()
}
placeFooter.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(footerCardMargin)
make.bottom.equalTo(container).offset(footerBottomOffset)
}
}
override func viewDidLayoutSubviews() {
updateMapViewMask()
}
private func updateMapViewMask() {
let diameter = mapView.bounds.width - mapViewMaskMargin * 2 // roughly duplicated in resetMapToUserLocation.
let rect = CGRect(x: mapViewMaskMargin, y: mapViewMaskMargin, width: diameter, height: diameter)
let ellipseInRect = CGPath(ellipseIn: rect, transform: nil)
mapViewMask.path = ellipseInRect
searchButtonTopConstraint.constant = rect.maxY
}
@objc private func closeWithButton() {
self.dismiss(animated: true)
delegate?.mapViewController(self, didDismissWithSelectedPlace: nil)
}
@objc private func closeWithSelected() {
self.dismiss(animated: true)
delegate?.mapViewController(self, didDismissWithSelectedPlace: selectedPlace)
}
override func viewWillAppear(_ animated: Bool) {
resetMapToUserLocation(shouldAnimate: false)
// Keep the old places on the map if we don't have them (should never happen).
guard let places = placesProvider?.getPlaces() else { return }
displayedPlaces = places.displayedPlaces
mapView.clear()
addToMap(places: displayedPlaces)
}
private func resetMapToUserLocation(shouldAnimate: Bool) {
guard let userCoordinate = locationProvider?.getCurrentLocation()?.coordinate else {
// TODO: do something clever
log.warn("Map view controller does not have current location")
return
}
searchButton.setIsHiddenWithAnimations(true)
// We want to display the full search circle in the map so we ensure the full search diameter
// can be seen in the the smallest dimension of the map view. One hack is we use view.frame,
// rather than mapView.frame, because mapView may not have been laid out in `viewWillAppear`.
// We could use another callback but they add complexity (e.g. didLayoutSubviews is called
// multiple times). Also, view.frame.width is the only dimension that is the same as the mapView
// so we assume it's the smallest dimension.
//
// One alternative is to use GMSMapView.cameraForBounds with something like: http://stackoverflow.com/a/6635926/2219998
// I could do that, but this already works. :)
let mapDiameterPoints = view.frame.width - mapViewMaskMargin * 2 - mapViewPaddingForPins // roughly duplicated in updateMapViewMask
let mapDiameterMeters = searchRadiusInMeters * 2 // convert radius to diameter.
let desiredZoom = GMSCameraPosition.zoom(at: userCoordinate, forMeters: mapDiameterMeters, perPoints: mapDiameterPoints)
let cameraUpdate = GMSCameraUpdate.setTarget(userCoordinate, zoom: desiredZoom)
if mapState == .normal { mapState = .movingByCode } // todo: checking against mapState everywhere is fragile.
if (!shouldAnimate) {
mapView.moveCamera(cameraUpdate)
} else {
mapView.animate(with: cameraUpdate)
}
}
private func addToMap(places: [Place]) {
// Consider limiting the place count if we hit performance issues.
for place in places {
let marker = GMSMarker(for: place)
marker.map = mapView
if place == selectedPlace {
updateSelected(marker: marker, andPlace: place)
}
}
}
@objc private func searchInVisibleArea() {
searchButton.isEnabled = false
mapView.clear()
UIView.animate(withDuration: fadeDuration) {
self.placeFooter.alpha = 0
}
// todo: calculate radius for zoom level.
let tmpRadius = searchRadiusInMeters / 1000
database.getPlaces(forLocation: CLLocation(coordinate: mapView.camera.target), withRadius: tmpRadius).upon(.main) { results in
let rawPlaces = results.flatMap { $0.successResult() }
self.displayedPlaces = PlaceUtilities.filter(places: rawPlaces, withFilters: self.enabledFilters)
guard self.displayedPlaces.count != 0 else {
self.present(self.getNoResultsController(), animated: true) {
self.searchButton.setIsHiddenWithAnimations(true)
}
return
}
self.addToMap(places: self.displayedPlaces)
self.searchButton.setIsHiddenWithAnimations(true)
}
}
private func getNoResultsController() -> UIAlertController {
let controller = UIAlertController(title: Strings.mapView.noResultsYet, message: nil, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: Strings.mapView.dismissNoResults, style: .default) { action in
controller.dismiss(animated: true)
}
controller.addAction(dismissAction)
return controller
}
fileprivate func updateSelected(marker newMarker: GMSMarker, andPlace newPlace: Place) {
selectedMarker?.updateMarker(forSelected: false)
selectedMarker = newMarker
selectedMarker?.updateMarker(forSelected: true)
selectedPlace = newPlace
placeFooter.update(for: newPlace)
if placeFooter.alpha != 1 {
UIView.animate(withDuration: fadeDuration) {
self.placeFooter.alpha = 1
}
}
}
}
extension MapViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
guard let placeID = marker.userData as? String,
let place = displayedPlaces.first(where: { $0.id == placeID }) else {
log.error("Unable to get place for marker data: \(marker.userData)")
return true // if we return false, the map will do move & display an overlay, which we don't want.
}
updateSelected(marker: marker, andPlace: place)
return true
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
switch mapState {
case .initializing:
// We init the map view with a position and then update the position so idleAt gets called.
// Since it happens before the view is seen, we ignore this first call.
mapState = .normal
case .movingByCode:
mapState = .normal // done moving.
case .normal:
if searchButton.isHidden {
searchButton.setIsHiddenWithAnimations(false) // e.g. finger dragged.
}
}
}
}
extension MapViewController: UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
transitionContext.containerView.addSubview(view)
view.layoutIfNeeded()
UIView.animate(withDuration: 0.2, animations: {
if transitionContext.viewController(forKey: .to) == self {
self.hideMapConstraints.forEach { $0.deactivate() }
self.showMapConstraints.forEach { $0.activate() }
} else {
self.showMapConstraints.forEach { $0.deactivate() }
self.hideMapConstraints.forEach { $0.activate() }
}
self.view.layoutIfNeeded()
}, completion: { _ in
transitionContext.completeTransition(true)
})
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.2
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
|
mpl-2.0
|
c86704bc3df7db8f94a723e71214b6b3
| 39.214724 | 170 | 0.681312 | 5.046189 | false | false | false | false |
VladislavJevremovic/WebcamViewer
|
WebcamViewer/Scenes/Viewer/ViewerViewController.swift
|
1
|
1909
|
//
// Copyright © 2019 Vladislav Jevremović. All rights reserved.
//
import UIKit
internal protocol ViewerDisplayLogic: AnyObject {
func displayCamera(_ camera: Camera)
}
internal final class ViewerViewController: UIViewController, ViewerDisplayLogic {
var interactor: ViewerBusinessLogic?
var router: ViewerRoutingLogic?
private let contentView = ViewerContentView.al_makeView()
override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
let localStore: LocalStore
init(localStore: LocalStore, delegate: ViewerRouterDelegate?) {
self.localStore = localStore
super.init(nibName: nil, bundle: nil)
let interactor = ViewerInteractor(localStore: localStore)
let presenter = ViewerPresenter()
let router = ViewerRouter()
interactor.presenter = presenter
presenter.viewController = self
router.viewController = self
router.delegate = delegate
self.interactor = interactor
self.router = router
setupView()
Timer.scheduledTimer(
withTimeInterval: 0.01,
repeats: true
) { [weak self] _ in
self?.interactor?.navigateToSelectedCamera()
}
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Methods
private func setupView() {
setupContentView()
}
private func setupContentView() {
view.addSubview(contentView)
contentView.onSwipeLeft = { [weak self] in
self?.interactor?.navigateToNextCamera()
}
contentView.onSwipeRight = { [weak self] in
self?.interactor?.navigateToPreviousCamera()
}
contentView.onSwipeUp = { [weak self] in
self?.router?.navigateToCameraSelection()
}
contentView.al_edgesEqualToSuperview()
}
// MARK: - ViewerDisplayLogic
func displayCamera(_ camera: Camera) {
contentView.updateWithCamera(camera)
}
}
|
mit
|
ed2990d19676437583b642a50ebb9d4c
| 26.637681 | 81 | 0.714211 | 4.476526 | false | false | false | false |
Detailscool/YHRefresh
|
YHRefresh/YHRefreshExtensions.swift
|
1
|
5607
|
//
// UIScrollView+YH_Refresh.swift
//
// Created by Detailscool on 16/3/28.
// Copyright © 2016年 Detailscool. All rights reserved.
//
import UIKit
var YHRefreshHeaderKey = "YHRefreshHeaderKey"
var YHRefreshFooterKey = "YHRefreshFooterKey"
public extension UIScrollView {
public class func initializeMethod() {
struct Static {
static let token: String = NSUUID().uuidString
}
DispatchQueue.once(token: Static.token) {
let originalSelector = NSSelectorFromString("dealloc")
let swizzledSelector = #selector(UIScrollView.yhDeinit)
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!);
}
}
}
@objc func yhDeinit() {
if let _ = yh_header {
removeObserver(yh_header!, forKeyPath: yh_RefreshContentOffsetKey)
removeObserver(yh_header!, forKeyPath: yh_RefreshContentSizeKey)
yh_header!.removeFromSuperview()
}
if let _ = yh_footer {
removeObserver(yh_footer!, forKeyPath: yh_RefreshContentOffsetKey)
removeObserver(yh_footer!, forKeyPath: yh_RefreshContentSizeKey)
yh_footer!.removeFromSuperview()
}
yhDeinit()
}
public var yh_header : YHRefreshHeader? {
get {
if let header = objc_getAssociatedObject(self, &YHRefreshHeaderKey) as? YHRefreshHeader {
return header
} else {
return nil
}
}
set {
if let _ = self.yh_header, self.yh_header != newValue {
self.yh_header!.removeFromSuperview()
}
self.addSubview(newValue!)
objc_setAssociatedObject(self, &YHRefreshHeaderKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
public var yh_footer : YHRefreshFooter? {
get {
if let footer = objc_getAssociatedObject(self, &YHRefreshFooterKey) as? YHRefreshFooter {
return footer
} else {
return nil
}
}
set {
if let _ = self.yh_footer, self.yh_footer != newValue {
self.yh_footer!.removeFromSuperview()
}
self.addSubview(newValue!)
objc_setAssociatedObject(self, &YHRefreshFooterKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
}
}
public var isHeaderRefreshing : Bool {
guard let header = yh_header else {
return false
}
return header.isRefreshing
}
public var isFooterRefreshing : Bool {
guard let footer = yh_footer else {
return false
}
return footer.isRefreshing
}
public var isRefreshing : Bool {
return isHeaderRefreshing || isFooterRefreshing
}
}
public extension Date {
func stringFromDate(_ format:String = "yyyy-MM-dd HH:mm:ss" ) -> String {
let dfm = DateFormatter()
dfm.dateFormat = format
dfm.locale = Locale(identifier: "en")
return dfm.string(from: self)
}
static func dateFromString(_ string:String, format:String = "yyyy-MM-dd HH:mm:ss") -> Date? {
let dfm = DateFormatter()
dfm.dateFormat = format
dfm.locale = Locale(identifier: "en")
return dfm.date(from: string)
}
func isToday() -> Bool {
return Calendar.current.isDateInToday(self)
}
func isYesterday() -> Bool {
return Calendar.current.isDateInYesterday(self)
}
}
public extension String {
func timeStateForRefresh(_ format:String = "yyyy-MM-dd HH:mm:ss") -> String {
let createDate = Date.dateFromString(self , format: format)
if let date = createDate {
if date.isToday() {
return yh_Titles[6] + "\(date.stringFromDate("HH:mm"))"
}else if date.isYesterday() {
return yh_Titles[7] + " \(date.stringFromDate("HH:mm"))"
}else {
return "\(date.stringFromDate("MM-dd HH:mm"))"
}
}
return self
}
}
public extension DispatchQueue {
private static var _onceTracker = [String]()
/**
Executes a block of code, associated with a unique token, only once. The code is thread safe and will
only execute the code once even in the presence of multithreaded calls.
- parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID
- parameter block: Block to execute once
*/
public class func once(token: String, block:()->Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
if _onceTracker.contains(token) {
return
}
_onceTracker.append(token)
block()
}
}
|
mit
|
7c6b67be3e4ef11ececa3ce84f8e4437
| 29.291892 | 154 | 0.57459 | 4.902887 | false | false | false | false |
insidegui/WWDC
|
WWDC/AppCommandsReceiver.swift
|
1
|
2872
|
//
// AppCommandsReceiver.swift
// WWDC
//
// Created by Guilherme Rambo on 26/05/21.
// Copyright © 2021 Guilherme Rambo. All rights reserved.
//
import Cocoa
import ConfCore
import os.log
final class AppCommandsReceiver {
private let log = OSLog(subsystem: "io.wwdc.app", category: String(describing: AppCommandsReceiver.self))
// swiftlint:disable:next cyclomatic_complexity
func handle(_ command: WWDCAppCommand, storage: Storage) -> DeepLink? {
os_log("%{public}@ %@", log: log, type: .debug, #function, String(describing: command))
switch command {
case .favorite(let id):
storage.setFavorite(true, onSessionsWithIDs: [id])
return nil
case .unfavorite(let id):
storage.setFavorite(false, onSessionsWithIDs: [id])
return nil
case .watch:
guard let session = command.session(in: storage) else { return nil }
storage.setWatched(true, on: session)
return nil
case .unwatch:
guard let session = command.session(in: storage) else { return nil }
storage.setWatched(false, on: session)
return nil
case .download:
guard let session = command.session(in: storage) else { return nil }
DownloadManager.shared.download([session])
return nil
case .cancelDownload:
guard let session = command.session(in: storage) else { return nil }
DownloadManager.shared.cancelDownloads([session])
return nil
case .revealVideo:
guard let link = DeepLink(from: command) else {
os_log("Failed to construct deep link from command: %{public}@", log: self.log, type: .error, String(describing: command))
return nil
}
return link
case .launchPreferences:
NSApp.sendAction(#selector(AppDelegate.showPreferences(_:)), to: nil, from: nil)
return nil
}
}
}
extension WWDCAppCommand {
var sessionId: String? {
switch self {
case .favorite(let id):
return id
case .unfavorite(let id):
return id
case .watch(let id):
return id
case .unwatch(let id):
return id
case .download(let id):
return id
case .cancelDownload(let id):
return id
case .revealVideo(let id):
return id
case .launchPreferences:
return nil
}
}
func session(in storage: Storage) -> Session? {
guard let id = sessionId else { return nil }
return storage.session(with: id)
}
}
|
bsd-2-clause
|
07f1e290b5e07ed8ab6ca327bf3dc37a
| 29.542553 | 138 | 0.552072 | 4.792988 | false | false | false | false |
screenworker/SwiftMenu
|
Example/SwiftMenu/AppDelegate.swift
|
1
|
7725
|
//
// AppDelegate.swift
// SwiftMenu Example
//
// Copyright © 2016 Peter Kreinz, Screenworker. All rights reserved. (http://www.screenworker.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Note: Also add a new row to Info.plist-> "View controller-based status bar appearance" = "No"
//UIApplication.sharedApplication().statusBarHidden = true
//navigation bar global appearance
UINavigationBar.appearance().isTranslucent = true
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: UIBarMetrics.default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor.white
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.screenworker.ios.SwiftMenuApp" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "SwiftMenuApp", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
a5fd9a44779cda6e31fa0ae85b9b294c
| 55.379562 | 291 | 0.722812 | 5.662757 | false | false | false | false |
perlmunger/NewFreeApps
|
LearningSwift.playground/section-1.swift
|
1
|
3254
|
// Playground - noun: a place where people can play
import UIKit
// Optionals
func getSomeOptionalObject() -> AnyObject? {
return "Hello World"
}
var obj: AnyObject? = getSomeOptionalObject()
obj!
// Arrays
var legacy = NSMutableArray()
legacy.addObject("orange")
legacy.addObject("blue")
legacy.addObject("green")
legacy.addObject("yellow")
let shiny:[String] = ["orange", "blue", "green", "yellow"]
//shiny.append("orange")
//shiny.append("blue")
//shiny.append("green")
//shiny.append("yellow")
shiny
// Objective-C way
var sorted = (shiny as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "self", ascending: true)])
sorted
// Sort alpha
var newSorted = shiny.sort({ $0.characters.count < $1.characters.count })
newSorted
// Filter with Objective-C
var filtered = (shiny as NSArray).filteredArrayUsingPredicate(NSPredicate(format: "self contains[cd] %@", "o"))
// Filter
var filtered2 = shiny.filter({($0 as NSString).containsString("o")})
filtered2
class CustomClass {
var color:String
init(color:String) {
self.color = color
}
}
func >(custom1:CustomClass, custom2:CustomClass) -> Bool{
return custom1.color.characters.count > custom1.color.characters.count
}
var c = "color"
var cc = CustomClass(color: "blue")
// Shortcut array creation
var objects = [CustomClass(color: "orange"),
CustomClass(color: "blue"),
CustomClass(color: "green"),
CustomClass(color: "yellow")]
var filtered75 = objects.filter({$0.color == "blue"})
filtered75[0]
objects.sort(>)
objects
var strings = "orange,blue,green,yellow".componentsSeparatedByString(",")
strings
strings.sort({ $0 < $1 })
strings
// Dynamic Object Creation
func createLayerOfType(clazz:CALayer.Type) -> CALayer {
// Create a layer dynamically
let layer = clazz.init()
// We know that all layers share a common base set of properties
layer.bounds = CGRect(x: 0.0, y: 0.0, width: 300.0, height: 200.0)
layer.position = CGPoint(x: 100.0, y: 100.0)
layer.backgroundColor = UIColor.blueColor().CGColor
layer.borderColor = UIColor.darkGrayColor().CGColor
layer.borderWidth = 4.0
layer.cornerRadius = 12.0
if layer is CAGradientLayer {
// Let's say our type is a Gradient Layer
// Typecast this local variable
let gradientLayer = layer as! CAGradientLayer
gradientLayer.colors = [UIColor.orangeColor().CGColor as AnyObject, UIColor.yellowColor().CGColor as AnyObject]
} else if layer is CAShapeLayer {
// Let's say our type is a Shape Layer
// Typecast this local variable
let shapeLayer = layer as! CAShapeLayer
shapeLayer.path = UIBezierPath(rect: layer.bounds).CGPath
} else if layer is CATextLayer {
// Let's say our type is a Text Layer
// Typecast this local variable
let textLayer = layer as! CATextLayer
textLayer.string = "Hello World!"
}
return layer
}
var gradientLayer = createLayerOfType(CAGradientLayer.self)
(gradientLayer as! CAGradientLayer).colors!.count
var shapeLayer = createLayerOfType(CAShapeLayer.self)
(shapeLayer as! CAShapeLayer).path
var textLayer = createLayerOfType(CATextLayer.self)
(textLayer as! CATextLayer).string
|
mit
|
46488421317dfd2fe164f9eb4c8318c6
| 25.455285 | 119 | 0.695759 | 3.968293 | false | false | false | false |
Deliany/yaroslav_skorokhid_SimplePins
|
yaroslav_skorokhid_SimplePins/FBOAuthViewController.swift
|
1
|
2414
|
//
// FBOAuthViewController.swift
// yaroslav_skorokhid_SimplePins
//
// Created by Yaroslav Skorokhid on 10/15/16.
// Copyright © 2016 CollateralBeauty. All rights reserved.
//
import UIKit
class FBOAuthViewController: UIViewController {
@IBOutlet private weak var webView: UIWebView!
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
var cancelClosure: ((controller: FBOAuthViewController) -> Void)?
var completionClosure: ((credentials: OAuthCredentials?, errorString: String?, controller: FBOAuthViewController) -> Void)?
private var socialOAuth: OAuthSocial!
override func viewDidLoad() {
super.viewDidLoad()
self.socialOAuth = FacebookOAuth()
let url = self.socialOAuth.OAuthURL()
self.socialOAuth.authorizeHandler = { [weak self] in
self?.webView.loadRequest(NSURLRequest(URL: url))
}
self.socialOAuth.authorizeCompletionClosure = { [weak self] (credentials: OAuthCredentials?, errorString: String?) -> Void in
guard let strongSelf = self else { return }
strongSelf.completionClosure?(credentials: credentials, errorString:errorString, controller: strongSelf)
}
self.activityIndicator.startAnimating()
self.socialOAuth.authorize()
}
@objc
@IBAction private func cancelButtonPressed(sender: AnyObject) {
self.cancelClosure?(controller: self)
}
}
extension FBOAuthViewController: UIWebViewDelegate {
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
var shouldStart = false
if let URL = request.URL where URL.host == self.socialOAuth.redirectURI.host ||
URL.absoluteString.rangeOfString("access_token=") != nil ||
URL.absoluteString.rangeOfString("error=") != nil {
self.socialOAuth.handleRedirectURL(URL)
}
else {
shouldStart = true
}
return shouldStart
}
func webViewDidFinishLoad(webView: UIWebView) {
self.activityIndicator.stopAnimating()
}
func webViewDidStartLoad(webView: UIWebView) {
self.activityIndicator.startAnimating()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
self.activityIndicator.stopAnimating()
}
}
|
mit
|
f0f0c8aad87b01de6f69851576fb334d
| 34.485294 | 137 | 0.682553 | 5.090717 | false | false | false | false |
mozilla-mobile/focus
|
content-blocker-lib-ios/ContentBlockerGen/Sources/ContentBlockerGen/main.swift
|
1
|
2544
|
/* 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 ContentBlockerGenLib
let fm = FileManager.default
let fallbackPath: String = (#file as NSString).deletingLastPathComponent + "/../.."
// We expect this command to be executed as 'cd <dir of swift package>; swift run', if not, use the fallback path generated from the path to main.swift. Running from an xcodeproj will use fallbackPath.
let execIsFromCorrectDir = fm.fileExists(atPath: fm.currentDirectoryPath + "/Package.swift")
let rootdir = execIsFromCorrectDir ? fm.currentDirectoryPath : fallbackPath
let blacklist = "\(rootdir)/../../Carthage/Checkouts/shavar-prod-lists/disconnect-blacklist.json"
let entityList = "\(rootdir)/../../Carthage/Checkouts/shavar-prod-lists/disconnect-entitylist.json"
let googleMappingList = "\(rootdir)/../../Carthage/Checkouts/shavar-prod-lists/google_mapping.json"
let fingerprintingList = "\(rootdir)/../../Carthage/Checkouts/shavar-prod-lists/normalized-lists/base-fingerprinting-track.json"
func jsonFrom(filename: String) -> [String: Any] {
let file = URL(fileURLWithPath: filename)
let data = try! Data(contentsOf: file)
return try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
}
let gen = ContentBlockerGenLib(entityListJson: jsonFrom(filename: entityList), googleMappingJson: jsonFrom(filename: googleMappingList))
let outputDir = URL(fileURLWithPath: "\(rootdir)/../../Lists")
func write(to outputDir: URL, action: Action, categories: [CategoryTitle]) {
for categoryTitle in categories {
let result = gen.parseBlacklist(json: jsonFrom(filename: blacklist), action: action, categoryTitle: categoryTitle)
let outputFile = "\(outputDir.path)/disconnect-\(categoryTitle.rawValue.lowercased()).json"
let output = "[\n" + result.joined(separator: ",\n") + "\n]"
removeAndReplace(filePath: outputFile, output: output)
}
}
func removeAndReplace(filePath: String, output: String) {
if fm.fileExists(atPath: filePath) {
do {
try fm.removeItem(atPath: filePath)
} catch let error {
print("error occurred, here are the details:\n \(error)")
}
}
try! output.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
}
write(to: outputDir, action: .blockAll, categories: [.Advertising, .Analytics, .Social, .Content])
|
mpl-2.0
|
a7e17ccf6588a88801d17a60882efb93
| 52 | 201 | 0.722091 | 3.889908 | false | false | false | false |
muenzpraeger/salesforce-einstein-vision-swift
|
SalesforceEinsteinVision/Classes/model/Label.swift
|
1
|
673
|
//
// Label.swift
// predictivevision
//
// Created by René Winkelmeyer on 02/28/2017.
// Copyright © 2016 René Winkelmeyer. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct Label {
public var id: Int?
public var datasetId: Int?
public var name: String?
public var numExamples: Int?
public var object: String?
init?() {
}
init?(jsonObject: SwiftyJSON.JSON) {
id = jsonObject["id"].int
datasetId = jsonObject["datasetId"].int
name = jsonObject["name"].string
numExamples = jsonObject["numExamples"].int
object = jsonObject["object"].string
}
}
|
apache-2.0
|
c075b3db4e65746d0734767e68a8d3c6
| 20.612903 | 59 | 0.625373 | 3.988095 | false | false | false | false |
thedreamer979/Calvinus
|
Calvin/GoToCalvinController.swift
|
1
|
2747
|
//
// CalvinMapView.swift
// Calvin
//
// Created by Arion Zimmermann on 05.03.17.
// Copyright © 2017 AZEntreprise. All rights reserved.
//
import UIKit
import MapKit
class GoToCalvinController : UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.map.delegate = self
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if #available(iOS 9.0, *) {
locationManager.requestLocation()
}
locationManager.startUpdatingLocation()
}
self.map.setUserTrackingMode(.follow, animated: true)
let annotation = Calvin()
self.map.addAnnotation(annotation)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: self.map.userLocation.coordinate, addressDictionary: nil))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: annotation.coordinate, addressDictionary: nil))
request.requestsAlternateRoutes = true
request.transportType = .walking
let directions = MKDirections(request: request)
directions.calculate {
(response, error) -> Void in
if let response = response {
for route in response.routes {
self.map.add((route.polyline))
}
} else {
if let error = error {
print(error)
AZEntrepriseServer.showError(controller: self, description: error.localizedDescription)
}
}
}
})
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = self.view.tintColor.withAlphaComponent(0.7)
renderer.lineWidth = 8.0
return renderer
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}
}
|
gpl-3.0
|
d04dca6d4518ea29d386106463eb038e
| 32.901235 | 132 | 0.588857 | 5.867521 | false | false | false | false |
Qminder/swift-api
|
Sources/Models/Ticket/Status.swift
|
1
|
396
|
//
// Status.swift
// QminderAPI
//
// Created by Kristaps Grinbergs on 01/02/2018.
//
import Foundation
/// Ticket status
public enum Status: String, Codable {
/// New
case new = "NEW"
/// Called
case called = "CALLED"
/// Cancelled by clerk
case cancelledByClerk = "CANCELLED_BY_CLERK"
/// No Show
case noShow = "NOSHOW"
/// Served
case served = "SERVED"
}
|
mit
|
0f543e97b2a82672d13dff2931544d8e
| 14.230769 | 48 | 0.618687 | 3.142857 | false | false | false | false |
austinzheng/swift
|
test/decl/protocol/special/coding/enum_coding_key_no_raw_type.swift
|
56
|
1389
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
enum ImplicitKey : CodingKey {
case a, b, c
}
for (index, (val, str)) in [(ImplicitKey.a, "a"), (.b, "b"), (.c, "c")].enumerated() {
// Keys with no raw type should get a stringValue which matches the case
// name.
guard val.stringValue == str else { fatalError() }
guard ImplicitKey(stringValue: str) == val else { fatalError() }
// They should not have an intValue.
guard val.intValue == nil else { fatalError() }
guard ImplicitKey(intValue: index) == nil else { fatalError() }
}
enum PartialImplicitKey : CodingKey {
case a, b, c
var intValue: Int? {
switch self {
case .a: return 1
case .b: return 2
case .c: return 3
}
}
var stringValue: String {
switch self {
case .a: return "A"
case .b: return "B"
case .c: return "C"
}
}
}
for (val, str, idx) in [(PartialImplicitKey.a, "a", 1), (.b, "b", 2), (.c, "c", 3)] {
guard val.stringValue == str.uppercased() else { fatalError() }
guard val.intValue == idx else { fatalError() }
// Keys which define some methods should still get derived conformance
// to the others.
guard PartialImplicitKey(stringValue: str) == val else { fatalError() }
guard PartialImplicitKey(intValue: idx) == nil else { fatalError() }
}
|
apache-2.0
|
6439cd73439b3db55926919a190ab61d
| 27.9375 | 86 | 0.595392 | 3.704 | false | false | false | false |
zisko/swift
|
test/IRGen/extension_type_metadata_linking.swift
|
1
|
1959
|
// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s
// REQUIRES: objc_interop
// Check that type metadata defined inside extensions of files imported from
// other modules is emitted with the right linkage.
//
// In particular, it should be possible to define types inside extensions of
// types imported from Foundation (rdar://problem/27245620).
import Foundation
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE4BaseCMm" = global
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE4BaseCMn" = constant
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE4BaseCMf" = internal global
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMm" = global
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMn" = constant
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMf" = internal global
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE6StructVMn" = constant
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE6StructVMf" = internal constant
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE4BaseCN" = alias
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE7DerivedCN" = alias
// CHECK-LABEL: @"$SSo8NSNumberC31extension_type_metadata_linkingE6StructVN" = alias
// CHECK-LABEL: define %swift.type* @"$SSo8NSNumberC31extension_type_metadata_linkingE4BaseCMa"()
// CHECK-LABEL: define %swift.type* @"$SSo8NSNumberC31extension_type_metadata_linkingE7DerivedCMa"
// FIXME: Not needed
// CHECK-LABEL: define %swift.type* @"$SSo8NSNumberC31extension_type_metadata_linkingE6StructVMa"
extension NSNumber {
public class Base : CustomStringConvertible {
public var description: String {
return "Base"
}
}
public class Derived : Base {
override public var description: String {
return "Derived"
}
}
public struct Struct {}
}
|
apache-2.0
|
02de206c056b6a4ec686e9f418d14ad3
| 38.979592 | 98 | 0.767739 | 3.607735 | false | false | false | false |
NUKisZ/MyTools
|
MyTools/MyTools/ThirdLibrary/EFQRCodeSource/EFQRCodeRecognizer.swift
|
1
|
2151
|
//
// EFQRCodeRecognizer.swift
// Pods
//
// Created by EyreFree on 2017/3/28.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreImage
public class EFQRCodeRecognizer {
public var image: CGImage? {
didSet {
contentArray = nil
}
}
var contents: [String]? {
get {
if nil == contentArray {
contentArray = getQRString()
}
return contentArray
}
}
private var contentArray: [String]?
public init(image: CGImage) {
self.image = image
}
// Get QRCodes from image
private func getQRString() -> [String]? {
guard let finalImage = self.image else {
return nil
}
let result = finalImage.toCIImage().recognizeQRCode(options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
if result.count <= 0 {
return finalImage.grayscale()?.toCIImage().recognizeQRCode(options: [CIDetectorAccuracy : CIDetectorAccuracyLow])
}
return result
}
}
|
mit
|
a63fa85080d8699b1f56362b4b6effa7
| 33.693548 | 125 | 0.672245 | 4.537975 | false | false | false | false |
huangboju/Moots
|
Examples/SwiftUI/Mac/NSTaskDemo/NSTaskDemo/ViewController.swift
|
1
|
5510
|
//
// ViewController.swift
// NSTaskDemo
//
// Created by alexiuce on 2017/7/27.
// Copyright © 2017年 alexiuce . All rights reserved.
//
import Cocoa
let kSelectedFilePath = "userSelectedPath"
class ViewController: NSViewController {
@IBOutlet weak var repoPath: NSTextField! // git 仓库path
@IBOutlet weak var savePath: NSTextField! // 本地保存路径
@IBOutlet var showInfoTextView: NSTextView! // 显示结果内容
var isLoadingRepo = false // 记录是否正在加载中..
var outputPipe = Pipe()
var task : Process?
override func viewDidLoad() {
super.viewDidLoad()
showInfoTextView.textColor = NSColor.white
// Do any additional setup after loading the view.
}
// 选择保存路径
@IBAction func selectPath(_ sender: NSButton) {
// 1. 创建打开文档面板对象
let openPanel = NSOpenPanel()
// 2. 设置确认按钮文字
openPanel.prompt = "Select"
// 3. 设置禁止选择文件
openPanel.canChooseFiles = true
// 4. 设置可以选择目录
openPanel.canChooseDirectories = true
// 5. 弹出面板框
openPanel.beginSheetModal(for: self.view.window!) { (result) in
// 6. 选择确认按钮
if result == .OK {
// 7. 获取选择的路径
self.savePath.stringValue = (openPanel.directoryURL?.path)!
// 8. 保存用户选择路径(为了可以在其他地方有权限访问这个路径,需要对用户选择的路径进行保存)
UserDefaults.standard.setValue(openPanel.url?.path, forKey: kSelectedFilePath)
UserDefaults.standard.synchronize()
}
// 9. 恢复按钮状态
sender.state = .off
}
}
// clone按钮事件:(这里名称用了pull,不想改了,大家自己使用的时候,最好使用clone来命名)
@IBAction func startPull(_ sender: NSButton) {
// guard let executePath = UserDefaults.standard.value(forKey: kSelectedFilePath) as? String else {
// print("no selected path")
// return
// }
let executePath = "/Users/jourhuang/Desktop/Test"
guard repoPath.stringValue != "" else {return}
if isLoadingRepo {return} // 如果正在执行,则返回
isLoadingRepo = true // 设置正在执行标记
task = Process() // 创建NSTask对象
// 设置task
task?.launchPath = "/bin/bash" // 执行路径(这里是需要执行命令的绝对路径)
// 设置执行的具体命令
task?.arguments = ["-c","cd \(executePath); git clone \(repoPath.stringValue)"]
task?.terminationHandler = { proce in // 执行结束的闭包(回调)
self.isLoadingRepo = false // 恢复执行标记
print("finished")
self.showFiles()
}
captureStandardOutputAndRouteToTextView(task!)
task?.launch() // 开启执行
task?.waitUntilExit() // 阻塞直到执行完毕
}
// 显示目录文档列表
fileprivate func showFiles() {
guard let executePath = UserDefaults.standard.value(forKey: kSelectedFilePath) as? String else {
print("no selected path")
return
}
let listTask = Process() // 创建NSTask对象
// 设置task
listTask.launchPath = "/bin/bash" // 执行路径(这里是需要执行命令的绝对路径)
// 设置执行的具体命令
listTask.arguments = ["-c","cd \(executePath + "/" + (repoPath.stringValue as NSString).lastPathComponent); ls "]
captureStandardOutputAndRouteToTextView(listTask)
listTask.launch() // 开启执行
listTask.waitUntilExit()
}
}
extension ViewController{
fileprivate func captureStandardOutputAndRouteToTextView(_ task:Process) {
//1. 设置标准输出管道
outputPipe = Pipe()
task.standardOutput = outputPipe
//2. 在后台线程等待数据和通知
outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
//3. 接受到通知消息
NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outputPipe.fileHandleForReading , queue: nil) { notification in
//4. 获取管道数据 转为字符串
let output = self.outputPipe.fileHandleForReading.availableData
let outputString = String(data: output, encoding: String.Encoding.utf8) ?? ""
if outputString != ""{
//5. 在主线程处理UI
DispatchQueue.main.async(execute: {
let previousOutput = self.showInfoTextView.string
let nextOutput = previousOutput + "\n" + outputString
self.showInfoTextView.string = nextOutput
// 滚动到可视位置
let range = NSRange(location:nextOutput.count,length:0)
self.showInfoTextView.scrollRangeToVisible(range)
})
}
//6. 继续等待新数据和通知
self.outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
}
}
}
|
mit
|
9179c480fc5ca795fb361a6da745e4b0
| 33.963768 | 174 | 0.577617 | 4.455217 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.