repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
q231950/appwatch
|
refs/heads/master
|
AppWatchLogic/AppWatchLogic/TimeWarehouses/TimeWarehouse.swift
|
mit
|
1
|
//
// TimeWarehouse.swift
// AppWatch
//
// Created by Martin Kim Dung-Pham on 16.08.15.
// Copyright © 2015 Martin Kim Dung-Pham. All rights reserved.
//
import Foundation
extension NSDate {
func endedWithinRange(from: NSDate, to: NSDate) -> Bool {
return (self.compare(to) == NSComparisonResult.OrderedAscending && self.compare(from) == NSComparisonResult.OrderedDescending) || self.compare(to) == NSComparisonResult.OrderedSame
}
func beganWithinRange(from: NSDate, to: NSDate) -> Bool {
return (self.compare(to) == NSComparisonResult.OrderedDescending && self.compare(from) == NSComparisonResult.OrderedAscending ) || self.compare(from) == NSComparisonResult.OrderedSame
}
}
protocol TimeWarehouse {
func timeBoxes(from: NSDate, to: NSDate, completion: ([TimeBox]?, NSError?) -> Void)
}
|
ff1f18de4f5be431b3c802f7cc0a7a2c
| 35.478261 | 191 | 0.708831 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue
|
refs/heads/master
|
iOS/Venue/Views/MyLocationAnnotation.swift
|
epl-1.0
|
1
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/// Subclass of VenueMapAnnotation. Represents an annotation for the user's current location.
class MyLocationAnnotation: VenueMapAnnotation {
var userObject: User!
private let imageName = "your_location"
private var referencePoint = CGPoint()
init(user: User, location: CGPoint) {
self.userObject = user
let backgroundImage = UIImage(named: imageName)!
// Setup the frame for the button
referencePoint = location
let x = self.referencePoint.x - (backgroundImage.size.width / 2)
let y = self.referencePoint.y - (backgroundImage.size.height / 2)
super.init(frame: CGRect(x: x, y: y, width: backgroundImage.size.width, height: backgroundImage.size.height))
self.setBackgroundImage(backgroundImage, forState: UIControlState.Normal)
self.accessibilityIdentifier = self.userObject.name
self.accessibilityHint = "Current User"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func updateLocation(mapZoomScale: CGFloat) {
self.center.x = (self.referencePoint.x * mapZoomScale)
self.center.y = (self.referencePoint.y * mapZoomScale)
}
override func updateReferencePoint(newReferencePoint: CGPoint, mapZoomScale: CGFloat) {
self.referencePoint = newReferencePoint
self.updateLocation(mapZoomScale)
}
override func annotationSelected(mapZoomScale: CGFloat) {
// Nothing happens for this type of annotation
}
override func getReferencePoint() -> CGPoint {
return self.referencePoint
}
}
|
d19f64163e0cbbe81c9a24032784c85e
| 32.396226 | 117 | 0.681356 | false | false | false | false |
devxoul/URLNavigator
|
refs/heads/master
|
Tests/URLMatcherTests/URLConvertibleSpec.swift
|
mit
|
1
|
import Foundation
import Nimble
import Quick
import URLMatcher
final class URLConvertibleSpec: QuickSpec {
override func spec() {
describe("urlValue") {
it("returns an URL instance") {
let url = URL(string: "https://xoul.kr")!
expect(url.urlValue) == url
expect(url.absoluteString.urlValue) == url
}
it("returns an URL instance from unicode string") {
let urlString = "https://xoul.kr/한글"
expect(urlString.urlValue) == URL(string: "https://xoul.kr/%ED%95%9C%EA%B8%80")!
}
}
describe("urlStringValue") {
it("returns a URL string value") {
let url = URL(string: "https://xoul.kr")!
expect(url.urlStringValue) == url.absoluteString
expect(url.absoluteString.urlStringValue) == url.absoluteString
}
}
describe("queryParameters") {
context("when there is no query string") {
it("returns empty dictionary") {
let url = "https://xoul.kr"
expect(url.urlValue?.queryParameters) == [:]
expect(url.urlStringValue.queryParameters) == [:]
}
}
context("when there is an empty query string") {
it("returns empty dictionary") {
let url = "https://xoul.kr?"
expect(url.urlValue?.queryParameters) == [:]
expect(url.urlStringValue.queryParameters) == [:]
}
}
context("when there is a query string") {
let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34&url=https://foo/bar?hello=world"
it("has proper keys") {
expect(Set(url.urlValue!.queryParameters.keys)) == ["key", "greeting", "int", "url"]
expect(Set(url.urlStringValue.queryParameters.keys)) == ["key", "greeting", "int", "url"]
}
it("decodes a percent encoding") {
expect(url.urlValue?.queryParameters["key"]) == "this is a value"
expect(url.urlStringValue.queryParameters["key"]) == "this is a value"
}
it("doesn't convert + to whitespace") {
expect(url.urlValue?.queryParameters["greeting"]) == "hello+world!"
expect(url.urlStringValue.queryParameters["greeting"]) == "hello+world!"
}
it("takes last value from duplicated keys") {
expect(url.urlValue?.queryParameters["int"]) == "34"
expect(url.urlStringValue.queryParameters["int"]) == "34"
}
it("has an url") {
expect(url.urlValue?.queryParameters["url"]) == "https://foo/bar?hello=world"
}
}
}
describe("queryItems") {
context("when there is no query string") {
it("returns nil") {
let url = "https://xoul.kr"
expect(url.urlValue?.queryItems).to(beNil())
expect(url.urlStringValue.queryItems).to(beNil())
}
}
context("when there is an empty query string") {
it("returns an empty array") {
let url = "https://xoul.kr?"
expect(url.urlValue?.queryItems) == []
expect(url.urlStringValue.queryItems) == []
}
}
context("when there is a query string") {
let url = "https://xoul.kr?key=this%20is%20a%20value&greeting=hello+world!&int=12&int=34"
it("has exact number of items") {
expect(url.urlValue?.queryItems?.count) == 4
expect(url.urlStringValue.queryItems?.count) == 4
}
it("decodes a percent encoding") {
expect(url.urlValue?.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value")
expect(url.urlStringValue.queryItems?[0]) == URLQueryItem(name: "key", value: "this is a value")
}
it("doesn't convert + to whitespace") {
expect(url.urlValue?.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!")
expect(url.urlStringValue.queryItems?[1]) == URLQueryItem(name: "greeting", value: "hello+world!")
}
it("takes all duplicated keys") {
expect(url.urlValue?.queryItems?[2]) == URLQueryItem(name: "int", value: "12")
expect(url.urlValue?.queryItems?[3]) == URLQueryItem(name: "int", value: "34")
expect(url.urlStringValue.queryItems?[2]) == URLQueryItem(name: "int", value: "12")
expect(url.urlStringValue.queryItems?[3]) == URLQueryItem(name: "int", value: "34")
}
}
}
}
}
|
a44ebce4f359cf84c7a14885a3c95136
| 35.289256 | 129 | 0.58506 | false | false | false | false |
tlax/looper
|
refs/heads/master
|
looper/Model/Camera/Compress/MCameraCompressItemSlight.swift
|
mit
|
1
|
import UIKit
class MCameraCompressItemSlight:MCameraCompressItem
{
private let kPercent:Int = 50
private let kRemoveInterval:Int = 1
init()
{
let title:String = NSLocalizedString("MCameraCompressItemSlight_title", comment:"")
let color:UIColor = UIColor(red:0.5, green:0.7, blue:0, alpha:1)
super.init(title:title, percent:kPercent, color:color)
}
override func compress(record:MCameraRecord) -> MCameraRecord?
{
let removeRecord:MCameraRecord = removeInterItems(
record:record,
intervalRemove:kRemoveInterval)
return removeRecord
}
}
|
407db6d3bac5acdd88d73ec8c06b71e2
| 26.5 | 91 | 0.648485 | false | false | false | false |
cpageler93/RAML-Swift
|
refs/heads/master
|
Sources/DocumentationEntry.swift
|
mit
|
1
|
//
// RAML+DocumentationEntry.swift
// RAML
//
// Created by Christoph Pageler on 24.06.17.
//
import Foundation
import Yaml
import PathKit
public class DocumentationEntry: HasAnnotations {
public var title: String
public var content: String
public var annotations: [Annotation]?
public init(title: String, content: String) {
self.title = title
self.content = content
}
internal init() {
self.title = ""
self.content = ""
}
}
// MARK: Documentation Parsing
internal extension RAML {
internal func parseDocumentation(_ input: ParseInput) throws -> [DocumentationEntry]? {
guard let yaml = input.yaml else { return nil }
switch yaml {
case .array(let yamlArray):
return try parseDocumentation(array: yamlArray, parentFilePath: input.parentFilePath)
case .string(let yamlString):
let (yaml, path) = try parseDocumentationEntriesFromIncludeString(yamlString, parentFilePath: input.parentFilePath)
guard let documentationEntriesArray = yaml.array else {
throw RAMLError.ramlParsingError(.invalidInclude)
}
return try parseDocumentation(array: documentationEntriesArray, parentFilePath: path)
default: return nil
}
}
private func parseDocumentation(array: [Yaml], parentFilePath: Path?) throws -> [DocumentationEntry] {
var documentation: [DocumentationEntry] = []
for yamlDocumentationEntry in array {
guard let title = yamlDocumentationEntry["title"].string else {
throw RAMLError.ramlParsingError(.missingValueFor(key: "title"))
}
guard var content = yamlDocumentationEntry["content"].string else {
throw RAMLError.ramlParsingError(.missingValueFor(key: "content"))
}
if isInclude(content) {
try testInclude(content)
guard let parentFilePath = parentFilePath else {
throw RAMLError.ramlParsingError(.invalidInclude)
}
content = try contentFromIncludeString(content, parentFilePath: parentFilePath)
}
let documentationEntry = DocumentationEntry(title: title, content: content)
documentationEntry.annotations = try parseAnnotations(ParseInput(yamlDocumentationEntry, parentFilePath))
documentation.append(documentationEntry)
}
return documentation
}
private func parseDocumentationEntriesFromIncludeString(_ includeString: String, parentFilePath: Path?) throws -> (Yaml, Path) {
return try parseYamlFromIncludeString(includeString, parentFilePath: parentFilePath, permittedFragmentIdentifier: "DocumentationItem")
}
}
public protocol HasDocumentationEntries {
var documentation: [DocumentationEntry]? { get set }
}
public extension HasDocumentationEntries {
func documentationEntryWith(title: String) -> DocumentationEntry? {
for documentationEntry in documentation ?? [] {
if documentationEntry.title == title {
return documentationEntry
}
}
return nil
}
func hasDocumentationEntryWith(title: String) -> Bool {
return documentationEntryWith(title: title) != nil
}
}
// MARK: Default Values
public extension DocumentationEntry {
public convenience init(initWithDefaultsBasedOn documentationEntry: DocumentationEntry) {
self.init()
self.title = documentationEntry.title
self.content = documentationEntry.content
self.annotations = documentationEntry.annotations?.map { $0.applyDefaults() }
}
public func applyDefaults() -> DocumentationEntry {
return DocumentationEntry(initWithDefaultsBasedOn: self)
}
}
|
8c34baac5094bf9a47a6bcd7926fdc01
| 32.141667 | 142 | 0.646719 | false | false | false | false |
lennet/proNotes
|
refs/heads/master
|
app/proNotes/Document/DocumentInstance.swift
|
mit
|
1
|
//
// DocumentInstance.swift
// proNotes
//
// Created by Leo Thomas on 29/11/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
@objc
protocol DocumentInstanceDelegate: class {
@objc optional func currentPageDidChange(_ page: DocumentPage)
@objc optional func didAddPage(_ index: Int)
@objc optional func didUpdatePage(_ index: Int)
}
class DocumentInstance {
static let sharedInstance = DocumentInstance()
var delegates = Set<UIViewController>()
var undoManager: UndoManager? {
get {
let manager = PagesTableViewController.sharedInstance?.undoManager
manager?.levelsOfUndo = 5
return manager
}
}
weak var currentPage: DocumentPage? {
didSet {
if currentPage != nil && oldValue != currentPage {
informDelegateToUpdateCurrentPage(currentPage!)
}
}
}
var document: Document? {
didSet {
if document != nil {
if oldValue == nil {
currentPage = document?.pages.first
}
}
}
}
func didUpdatePage(_ index: Int) {
document?.updateChangeCount(.done)
informDelegateDidUpdatePage(index)
}
func save(_ completionHandler: ((Bool) -> Void)?) {
document?.save(to: document!.fileURL, for: .forOverwriting, completionHandler: completionHandler)
}
func flushUndoManager() {
undoManager?.removeAllActions()
NotificationCenter.default.post(name: NSNotification.Name.NSUndoManagerWillUndoChange, object: nil)
}
// MARK: - NSUndoManager
func registerUndoAction(_ object: Any?, pageIndex: Int, layerIndex: Int) {
(undoManager?.prepare(withInvocationTarget: self) as? DocumentInstance)?.undoAction(object, pageIndex: pageIndex, layerIndex: layerIndex)
}
func undoAction(_ object: Any?, pageIndex: Int, layerIndex: Int) {
if let pageView = PagesTableViewController.sharedInstance?.currentPageView {
if pageView.page?.index == pageIndex {
if let pageSubView = pageView[layerIndex] {
pageSubView.undoAction?(object)
return
}
}
}
// Swift 😍
document?[pageIndex]?[layerIndex]?.undoAction(object)
}
// MARK: - Delegate Handling
func addDelegate(_ delegate: DocumentInstanceDelegate) {
if let viewController = delegate as? UIViewController {
if !delegates.contains(viewController) {
delegates.insert(viewController)
}
}
}
func removeDelegate(_ delegate: DocumentInstanceDelegate) {
if let viewController = delegate as? UIViewController {
if delegates.contains(viewController) {
delegates.remove(viewController)
}
}
}
func removeAllDelegates() {
for case let delegate as DocumentInstanceDelegate in delegates {
removeDelegate(delegate)
}
}
func informDelegateToUpdateCurrentPage(_ page: DocumentPage) {
for case let delegate as DocumentInstanceDelegate in delegates {
delegate.currentPageDidChange?(page)
}
}
func informDelegateDidAddPage(_ index: Int) {
for case let delegate as DocumentInstanceDelegate in delegates {
delegate.didAddPage?(index)
}
}
func informDelegateDidUpdatePage(_ index: Int) {
for case let delegate as DocumentInstanceDelegate in delegates {
delegate.didUpdatePage?(index)
}
}
}
|
14e29c19480aae40609714f73e86387e
| 28.285714 | 145 | 0.612466 | false | false | false | false |
KoalaTeaCode/KoalaTeaPlayer
|
refs/heads/master
|
KoalaTeaPlayer/Classes/YTView/YTViewControllerPresenters.swift
|
mit
|
1
|
//
// YTViewControllerPresenter.swift
// KoalaTeaPlayer
//
// Created by Craig Holliday on 12/6/17.
//
import UIKit
open class YTViewControllerPresenter: UIViewController {
var ytNavigationController: YTViewController? = nil
override open func viewDidLoad() {
super.viewDidLoad()
guard let navigationController = self.navigationController as? YTViewController else {
print("The navigation controller is not a YTViewController")
return
}
self.ytNavigationController = navigationController
self.ytNavigationController?.ytViewControllerDelegate = self
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open func loadYTPlayerViewWith(assetName: String, videoURL: URL, artworkURL: URL? = nil, savedTime: Float = 0) {
guard let ytNavigationController = ytNavigationController else { return }
ytNavigationController.loadYTPlayerViewWith(assetName: assetName, videoURL: videoURL, artworkURL: artworkURL, savedTime: savedTime)
self.hideStatusBar()
}
open func showStatusBar() {
statusBarShouldBeHidden = false
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open func hideStatusBar() {
statusBarShouldBeHidden = true
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open var statusBarShouldBeHidden = false
override open var prefersStatusBarHidden: Bool {
return statusBarShouldBeHidden
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
extension YTViewControllerPresenter: YTViewControllerDelegate {
public func didMinimize() {
showStatusBar()
}
public func didmaximize() {
hideStatusBar()
}
public func didSwipeAway() {
}
}
open class YTViewControllerTablePresenter: UITableViewController {
var ytNavigationController: YTViewController? = nil
override open func viewDidLoad() {
super.viewDidLoad()
guard let navigationController = self.navigationController as? YTViewController else {
print("The navigation controller is not a YTViewController")
return
}
self.ytNavigationController = navigationController
self.ytNavigationController?.ytViewControllerDelegate = self
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open func loadYTPlayerViewWith(assetName: String, videoURL: URL, artworkURL: URL? = nil, savedTime: Float = 0) {
guard let ytNavigationController = ytNavigationController else { return }
ytNavigationController.loadYTPlayerViewWith(assetName: assetName, videoURL: videoURL, artworkURL: artworkURL, savedTime: savedTime)
self.hideStatusBar()
}
open func showStatusBar() {
statusBarShouldBeHidden = false
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open func hideStatusBar() {
statusBarShouldBeHidden = true
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open var statusBarShouldBeHidden = false
override open var prefersStatusBarHidden: Bool {
return statusBarShouldBeHidden
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
extension YTViewControllerTablePresenter: YTViewControllerDelegate {
public func didMinimize() {
showStatusBar()
}
public func didmaximize() {
hideStatusBar()
}
public func didSwipeAway() {
}
}
open class YTViewControllerCollectionPresenter: UICollectionViewController {
var ytNavigationController: YTViewController? = nil
override open func viewDidLoad() {
super.viewDidLoad()
guard let navigationController = self.navigationController as? YTViewController else {
print("The navigation controller is not a YTViewController")
return
}
self.ytNavigationController = navigationController
self.ytNavigationController?.ytViewControllerDelegate = self
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
open func loadYTPlayerViewWith(assetName: String, videoURL: URL, artworkURL: URL? = nil, savedTime: Float = 0) {
guard let ytNavigationController = ytNavigationController else { return }
ytNavigationController.loadYTPlayerViewWith(assetName: assetName, videoURL: videoURL, artworkURL: artworkURL, savedTime: savedTime)
self.hideStatusBar()
}
open func showStatusBar() {
statusBarShouldBeHidden = false
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open func hideStatusBar() {
statusBarShouldBeHidden = true
UIView.animate(withDuration: 0.25) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
open var statusBarShouldBeHidden = false
override open var prefersStatusBarHidden: Bool {
return statusBarShouldBeHidden
}
override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
extension YTViewControllerCollectionPresenter: YTViewControllerDelegate {
public func didMinimize() {
showStatusBar()
}
public func didmaximize() {
hideStatusBar()
}
public func didSwipeAway() {
}
}
|
b85ec26818013135c6120db62045f28a
| 28.832512 | 139 | 0.670244 | false | false | false | false |
billdonner/sheetcheats9
|
refs/heads/master
|
sc9/EditTilesViewController.swift
|
apache-2.0
|
1
|
//
// EditTilesViewController.swift
//
// Created by william donner on 9/29/15.
import UIKit
class TileSequeArgs {
var name:String = "",key:String = "",bpm:String = "",
textColor:UIColor = Colors.tileTextColor(),
backColor:UIColor = Colors.tileColor()
}
final class EditingTileCell: UICollectionViewCell {
@IBOutlet var alphabetLabel: UILabel!
func configureCellFromTile(_ t:Tyle) {
let name = t.tyleTitle
self.backgroundColor = t.tyleBackColor
self.alphabetLabel.text = name
self.alphabetLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyleHeadline)
self.alphabetLabel.textColor = Corpus.findFast(name) ? t.tyleTextColor : Colors.gray
}
}
final class EditTilesViewController: UICollectionViewController , ModelData {
let formatter = DateFormatter() // create just once
func refresh() { // DOES NOT SAVE DATAMODEL
self.collectionView?.backgroundColor = Colors.mainColor()
self.view.backgroundColor = Colors.mainColor()
self.collectionView?.reloadData()
}
var addSectionBBI: UIBarButtonItem!
@IBAction func editSections() {
self.presentSectionEditor(self)
}
// total surrender to storyboards, everything is done thru performSegue and unwindtoVC
@IBAction func unwindToEditTilesViewController(_ segue: UIStoryboardSegue) {
// print("Unwound to EditTilesViewController")
}
@IBAction func finallyDone(_ sender: AnyObject) {
// self.removeLastSpecialElements() // clean this up on way out
self.unwindToSurface (self)
}
var currentTileIdx:IndexPath?
var observer1 : NSObjectProtocol? // emsure ots retained
deinit{
NotificationCenter.default.removeObserver(observer1!)
self.cleanupFontSizeAware(self)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .lightContent
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// self.navigationItem.leftBarButtonItem?.enabled =
if self.sectCount() == 0 {
formatter.dateStyle = .short
formatter.timeStyle = .medium
let sectitle = "autogenerated " + formatter.string(from: Date())
let ip = IndexPath(row:0, section:0)
self.makeHeaderAt(ip , labelled: sectitle)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = Colors.mainColor()
self.view.backgroundColor = Colors.mainColor()
self.setupFontSizeAware(self)
observer1 = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: kSurfaceUpdatedSignal), object: nil, queue: OperationQueue.main) { _ in
print ("Surface was updated, edittilesviewController reacting....")
self.refresh()
}
}
}
// MARK: - UICollectionViewDelegate
// these would be delegates but that is already done because using UICollectionViewController
extension EditTilesViewController {
//: UICollectionViewDelegate{
override func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let tyle = self.tileData(indexPath)
// prepare for seque here
let tsarg = TileSequeArgs()
// set all necessary fields
tsarg.name = tyle.tyleTitle
tsarg.key = tyle.tyleKey
tsarg.bpm = tyle.tyleBpm
tsarg.textColor = tyle.tyleTextColor
tsarg.backColor = tyle.tyleBackColor
self.storeIndexArgForSeque(indexPath)
self.storeTileArgForSeque(tsarg)
self.presentEditTile(self)
}
}
// MARK: - UICollectionViewDataSource
extension EditTilesViewController {
//: UICollectionViewDataSource {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.tileSectionCount()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.tileCountInSection(section)
}
override func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
//1
switch kind {
//2
case UICollectionElementKindSectionHeader:
//3
let headerView =
collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: "sectionheaderid",
for: indexPath)
as! TilesSectionHeaderView
headerView.headerLabel.text = self.sectHeader((indexPath as NSIndexPath).section)[SectionProperties.NameKey]
headerView.headerLabel.textColor = Colors.headerTextColor()
headerView.headerLabel.backgroundColor = Colors.headerColor()
headerView.headerLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyleHeadline)
headerView.tag = (indexPath as NSIndexPath).section
// add a tap gesture recognizer
let tgr = UITapGestureRecognizer(target: self,action:#selector(EditTilesViewController.headerTapped(_:)))
headerView.addGestureRecognizer(tgr)
return headerView
default:
//4
fatalError( "Unexpected element kind")
}
}
func headerTapped(_ tgr:UITapGestureRecognizer) {
let v = tgr.view
if v != nil {
let sec = v!.tag // numeric section number
let max = tileCountInSection(sec)
let indexPath = IndexPath(item:max,section:sec)
//Create the AlertController
let actionSheetController: UIAlertController = UIAlertController(title: "Actions For This Section \(sec) ?", message: "Can not be undone", preferredStyle: .actionSheet )
//
// //Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
// Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
//Create and add first option action
actionSheetController.addAction(UIAlertAction(title: "New Tile", style: .default ) { action -> Void in
let _ = self.makeTileAt(indexPath,labelled:"\(sec) - \(max)")
self.refresh()
Globals.saveDataModel()
// self.unwindToMainMenu(self)
})
//Create and add first option action
actionSheetController.addAction(UIAlertAction(title: "Rename This Section", style: .default ) { action -> Void in
self.storeIntArgForSeque(sec)
self.presentSectionRenamor(self)
// self.unwindToMainMenu(self)
})
// We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = tgr.view! as UIView
// Present the AlertController
self.present(actionSheetController, animated: true, completion: nil)
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 3
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EditingTileCellID", for: indexPath) as! EditingTileCell
// Configure the cell
cell.configureCellFromTile(self.tileData(indexPath))
return cell
}
override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath) {
//if sourceIndexPath.section != destinationIndexPath.section {
mswap2(sourceIndexPath, destinationIndexPath)
// }
// else {
// mswap(sourceIndexPath, destinationIndexPath)
// }
}
}
extension EditTilesViewController:SegueHelpers {
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
self.prepForSegue(segue , sender: sender)
if let uiv = segue.destinationViewController as? ThemePickerViewController {
uiv.modalPresentationStyle = .fullScreen
uiv.delegate = self
}
if let uiv = segue.destinationViewController as? SectionRenamorViewController {
uiv.modalPresentationStyle = .fullScreen
uiv.sectionNum = self.fetchIntArgForSegue()
}
if let uiv = segue.destinationViewController as? SectionsEditorViewController {
uiv.modalPresentationStyle = .fullScreen
uiv.delegate = self
}
if let uiv = segue.destinationViewController as?
TilePropertiesEditorViewController {
// record which cell we are sequeing away from even if we never tell the editor
self.currentTileIdx = self.fetchIndexArgForSegue()
uiv.modalPresentationStyle = .fullScreen
uiv.tileIncoming = self.fetchTileArgForSegue()
uiv.tileIdx = self.currentTileIdx
uiv.delegate = self
}
}
}
extension EditTilesViewController: FontSizeAware {
func refreshFontSizeAware(_ vc: TilesViewController) {
vc.collectionView?.reloadData()
}
}
extension EditTilesViewController:ThemePickerDelegate {
func themePickerReturningResults(_ data:NSArray) {
print ("In edittiles theme returned \(data)")
}
}
extension EditTilesViewController: ShowContentDelegate {
func userDidDismiss() {
print("user dismissed Content View Controller")
}
}
// only the editing version of this controller gets these extra elegates
extension EditTilesViewController:TilePropertiesEditorDelegate {
func deleteThisTile() {
if self.currentTileIdx != nil {
self.tileRemove(self.currentTileIdx!)
Globals.saveDataModel()
refresh()
}
}
func tileDidUpdate(name:String,key:String,bpm:String,textColor:UIColor, backColor:UIColor){
if self.currentTileIdx != nil {
let tyle = elementFor(self.currentTileIdx!)
tyle.tyleTitle = name
tyle.tyleBpm = bpm
tyle.tyleKey = key
tyle.tyleTextColor = textColor
tyle.tyleBackColor = backColor
setElementFor(self.currentTileIdx!, el: tyle)
if let cell = self.collectionView?.cellForItem(at: self.currentTileIdx!) as? EditingTileCell {
//
// print ("updating tile at \(self.currentTileIdx!) ")
//
// cell.alphabetLabel.text = name
// cell.alphabetLabel.backgroundColor = backColor
// cell.alphabetLabel.textColor = textColor
cell.configureCellFromTile(tyle)
}
Globals.saveDataModel()
refresh()
}
}
}
extension EditTilesViewController: SectionsEditorDelegate {
func makeNewSection(_ i:Int) {
formatter.dateStyle = .short
formatter.timeStyle = .medium
let sectitle = formatter.string(from: Date())
let ip = IndexPath(row:i, section:0)
self.makeHeaderAt(ip , labelled: sectitle)
Globals.saveDataModel()
refresh()
}
func deleteSection(_ i: Int) { // removes whole section without a trace
self.deleteSect(i)
Globals.saveDataModel()
refresh()
}
func moveSections(_ from:Int,to:Int) {
self.moveSects(from, to)
Globals.saveDataModel()
refresh()
}
}
/// all the IB things need to be above here in the final classes
|
f2b11c4f306f62582d503a5e1d82f7ae
| 36.201201 | 181 | 0.627704 | false | false | false | false |
Shivol/Swift-CS333
|
refs/heads/master
|
assignments/task5/schedule/schedule/MasterViewController+DataLoaderDelegate.swift
|
mit
|
2
|
//
// MasterViewController+DataLoaderDelegate.swift
// schedule
//
// Created by Илья Лошкарёв on 30.03.17.
// Copyright © 2017 mmcs. All rights reserved.
//
import UIKit
extension MasterViewController: DataLoaderDelegate {
func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith data: Any?) {
switch dataLoader {
case is TimetableDataLoader:
guard let loadedTimetable = data as? Timetable else {
fatalError("unexpected data")
}
self.timetable = loadedTimetable
if self.currentWeek != nil {
self.timetable!.currentWeek = self.currentWeek!
}
if let activity = tableView.backgroundView as? UIActivityIndicatorView {
activity.removeFromSuperview()
activity.stopAnimating()
}
tableView.reloadData()
case is WeekDataLoader:
guard let loadedWeek = data as? AlternatingWeek else {
fatalError("unexpected data")
}
self.currentWeek = loadedWeek
if self.timetable != nil{
self.timetable!.currentWeek = loadedWeek
tableView.reloadData()
}
default:
fatalError("unexpected loader")
}
}
func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith error: NSError) {
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true)
}
}
|
bf31639e1c97950de54a8ad69d122494
| 31.226415 | 105 | 0.581967 | false | false | false | false |
limaoxuan/MXAlertView
|
refs/heads/master
|
MXAlertView/MXAlertView/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// MXAlertView
//
// Created by 李茂轩 on 15/2/6.
// Copyright (c) 2015年 lee. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var button : UIButton?
var mxAlertView : MXAlertView?
func initSubViews(){
mxAlertView = MXAlertView()
self.view.addSubview(mxAlertView!)
button = UIButton()
button?.setTitle("show/hidden", forState: UIControlState.Normal)
button?.backgroundColor = UIColor.blackColor()
button?.setTranslatesAutoresizingMaskIntoConstraints(false)
button?.addTarget(self, action: Selector("clickButton:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button!)
let viewDic = (["button":button!]) as NSDictionary
let locationH = "H:[button]"
let locationY = "V:|-50-[button(30)]"
setConstraintsWithStringHandVWithCurrentView(locationH, locationY, self.view, viewDic)
setLocationAccrodingWithSuperViewAndCurrentViewSetLayoutAttributeCenterX(self.view, button!, 200)
let s = Selector("clickButton:")
}
@objc func clickButton(obj:AnyObject!){
if mxAlertView?.isOpen == false {
mxAlertView?.showAlertAnimation()
}else if mxAlertView?.isOpen == true {
mxAlertView?.hiddenAlertAnimation()
}
}
override func viewDidLoad() {
super.viewDidLoad()
initSubViews()
// 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.
}
}
|
1e8b471596a400afdd7693c51449be55
| 20.222222 | 114 | 0.590052 | false | false | false | false |
knutigro/AppReviews
|
refs/heads/develop
|
AppReviews/StatusMenuController.swift
|
gpl-3.0
|
1
|
//
// StatusMenu.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-04-16.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import AppKit
class StatusMenuController: NSObject {
var statusItem: NSStatusItem!
var applications = [Application]()
var newReviews = [Int]()
var applicationArrayController: ApplicationArrayController!
private var kvoContext = 0
// MARK: - Init & teardown
deinit {
removeObserver(self, forKeyPath: "applications", context: &kvoContext)
}
override init() {
super.init()
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) // NSVariableStatusItemLength
statusItem.image = NSImage(named: "stausBarIcon")
statusItem.alternateImage = NSImage(named: "stausBarIcon")
statusItem.highlightMode = true
applicationArrayController = ApplicationArrayController(content: nil)
applicationArrayController.managedObjectContext = ReviewManager.managedObjectContext()
applicationArrayController.entityName = kEntityNameApplication
do {
try applicationArrayController.fetchWithRequest(nil, merge: true)
} catch let error as NSError {
print(error)
}
bind("applications", toObject: applicationArrayController, withKeyPath: "arrangedObjects", options: nil)
addObserver(self, forKeyPath: "applications", options: .New, context: &kvoContext)
_ = NSNotificationCenter.defaultCenter().addObserverForName(kDidUpdateApplicationNotification, object: nil, queue: nil) { notification in
}
_ = NSNotificationCenter.defaultCenter().addObserverForName(kDidUpdateApplicationSettingsNotification, object: nil, queue: nil) { [weak self] notification in
self?.updateMenu()
}
updateMenu()
}
// MARK: - Handling menu items
func updateMenu() {
let menu = NSMenu()
var newReviews = false
var idx = 1
for application in applications {
// application.addObserver(self, forKeyPath: "settings.newReviews", options: .New, context: &kvoContext)
var title = application.trackName
if application.settings.newReviews.integerValue > 0 {
newReviews = true
title = title + " (" + String(application.settings.newReviews.integerValue) + ")"
}
let shortKey = idx < 10 ? String(idx) : ""
let menuItem = NSMenuItem(title: title, action: Selector("openReviewsForApp:"), keyEquivalent: shortKey)
menuItem.representedObject = application
menuItem.target = self
menu.addItem(menuItem)
idx++
}
if (applications.count > 0) {
menu.addItem(NSMenuItem.separatorItem())
}
let menuItemApplications = NSMenuItem(title: NSLocalizedString("Add / Remove Applications", comment: "statusbar.menu.applications"), action: Selector("openApplications:"), keyEquivalent: "a")
let menuItemAbout = NSMenuItem(title: NSLocalizedString("About Appstore Reviews", comment: "statusbar.menu.about"), action: Selector("openAbout:"), keyEquivalent: "")
let menuItemProvidFeedback = NSMenuItem(title: NSLocalizedString("Provide Feedback...", comment: "statusbar.menu.feedback"), action: Selector("openFeedback:"), keyEquivalent: "")
let menuItemQuit = NSMenuItem(title: NSLocalizedString("Quit", comment: "statusbar.menu.quit"), action: Selector("quit:"), keyEquivalent: "q")
let menuItemLaunchAtStartup = NSMenuItem(title: NSLocalizedString("Launch at startup", comment: "statusbar.menu.startup"), action: Selector("launchAtStartUpToggle:"), keyEquivalent: "")
menuItemLaunchAtStartup.state = NSApplication.shouldLaunchAtStartup() ? NSOnState : NSOffState
menuItemApplications.target = self
menuItemAbout.target = self
menuItemQuit.target = self
menuItemProvidFeedback.target = self
menuItemLaunchAtStartup.target = self
menu.addItem(menuItemApplications)
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(menuItemLaunchAtStartup)
menu.addItem(menuItemProvidFeedback)
menu.addItem(NSMenuItem.separatorItem())
menu.addItem(menuItemAbout)
menu.addItem(menuItemQuit)
statusItem.menu = menu;
if newReviews {
statusItem.image = NSImage(named: "stausBarIconHappy")
statusItem.alternateImage = NSImage(named: "stausBarIconHappy")
} else {
statusItem.image = NSImage(named: "stausBarIcon")
statusItem.alternateImage = NSImage(named: "stausBarIcon")
}
}
}
// MARK: - Actions
extension StatusMenuController {
func openReviewsForApp(sender: AnyObject?) {
if let menuItem = sender as? NSMenuItem {
if let application = menuItem.representedObject as? Application {
ReviewWindowController.show(application.objectID)
}
}
}
func openAbout(sender: AnyObject?) {
let appdelegate = NSApplication.sharedApplication().delegate as! AppDelegate
let windowController = appdelegate.aboutWindowController
windowController.showWindow(self)
NSApp.activateIgnoringOtherApps(true)
}
func openApplications(sender: AnyObject?) {
let appdelegate = NSApplication.sharedApplication().delegate as! AppDelegate
let windowController = appdelegate.applicationWindowController
windowController.showWindow(self)
NSApp.activateIgnoringOtherApps(true)
}
func openFeedback(sender: AnyObject?) {
NSWorkspace.sharedWorkspace().openURL(NSURL(string: "http://knutigro.github.io/apps/app-reviews/#Feedback")!)
}
func launchAtStartUpToggle(sender : AnyObject?) {
if let menu = sender as? NSMenuItem {
NSApplication.toggleShouldLaunchAtStartup()
menu.state = NSApplication.shouldLaunchAtStartup() ? NSOnState : NSOffState
}
}
func quit(sender: AnyObject?) {
NSApplication.sharedApplication().terminate(sender)
}
}
// MARK: - KVO
extension StatusMenuController {
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &kvoContext {
// print("observeValueForKeyPath: " + keyPath + "change: \(change)" )
// updateMenu()
}
else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
}
|
34e3d55c48c441e3a798a86c91dc343a
| 37.644068 | 199 | 0.655359 | false | false | false | false |
imzyf/99-projects-of-swift
|
refs/heads/master
|
031-stopwatch/031-stopwatch/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// 031-stopwatch
//
// Created by moma on 2018/3/28.
// Copyright © 2018年 yifans. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - UI components
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var lapTimerLabel: UILabel!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var lapRestButton: UIButton!
@IBOutlet weak var lapsTableView: UITableView!
// MARK: - Variables
fileprivate let mainStopwatch: Stopwatch = Stopwatch()
fileprivate let lapStopwatch: Stopwatch = Stopwatch()
fileprivate var isPlay: Bool = false
fileprivate var laps: [String] = []
let stepTimeInterval: CGFloat = 0.035
override func viewDidLoad() {
super.viewDidLoad()
// 闭包设置 button 样式
let initCircleButton: (UIButton) -> Void = { button in
button.layer.cornerRadius = 0.5 * button.bounds.size.width
}
initCircleButton(playPauseButton)
initCircleButton(lapRestButton)
playPauseButton.setTitle("Stop", for: .selected)
lapRestButton.isEnabled = false
}
@IBAction func playPauseTimer(_ sender: UIButton) {
if sender.isSelected {
// stop
mainStopwatch.timer.invalidate()
} else {
// start
lapRestButton.isEnabled = true
mainStopwatch.timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(self.stepTimeInterval), repeats: true) { (time) in
self.updateTimer(self.mainStopwatch, label: self.timerLabel)
}
sender.isSelected = !sender.isSelected
//
// Timer.scheduledTimer(timeInterval: 0.035, target: self, selector: Selector.updateMainTimer, userInfo: nil, repeats: true)
//
}
}
func updateTimer(_ stopwatch: Stopwatch, label: UILabel) {
stopwatch.counter = stopwatch.counter + stepTimeInterval
let minutes = Int(stopwatch.counter / 60)
let minuteText = minutes < 10 ? "0\(minutes)" : "\(minutes)"
let seconds = stopwatch.counter.truncatingRemainder(dividingBy: 60)
let secondeText = seconds < 10 ? String(format: "0%.2f", seconds) : String(format: "%.2f", seconds)
label.text = minuteText + ":" + secondeText
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return laps.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath)
// if let labelNum = cell.viewWithTag(11) as? UILabel {
// labelNum.text = "Lap \(laps.count - (indexPath as NSIndexPath).row)"
// }
// if let labelTimer = cell.viewWithTag(12) as? UILabel {
// labelTimer.text = laps[laps.count - (indexPath as NSIndexPath).row - 1]
// }
return cell
}
}
|
1f8d61e743aa10ccbc28af6ffd66015b
| 31.69 | 139 | 0.609055 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new
|
refs/heads/master
|
Source/DiscussionTestsDataFactory.swift
|
apache-2.0
|
5
|
//
// DiscussionTestsDataFactory.swift
// edX
//
// Created by Saeed Bashir on 2/25/16.
// Copyright © 2016 edX. All rights reserved.
//
@testable import edX
import UIKit
import XCTest
class DiscussionTestsDataFactory: NSObject {
static let thread = DiscussionThread(
threadID: "123",
type: .Discussion,
courseId: "some-course",
topicId: "abc",
groupId: nil,
groupName: nil,
title: "Some Post",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: "Staff",
commentCount: 0,
commentListUrl: nil,
hasEndorsed: false,
pinned: false,
closed: false,
following: false,
flagged: false,
abuseFlagged: false,
voted: true,
voteCount: 4,
createdAt: NSDate.stableTestDate(),
updatedAt: NSDate.stableTestDate(),
editableFields: nil,
read: true,
unreadCommentCount: 0,
responseCount: 0,
hasProfileImage: false,
imageURL: nil)
static let unreadThread = DiscussionThread(
threadID: "123",
type: .Discussion,
courseId: "some-course",
topicId: "abc",
groupId: nil,
groupName: nil,
title: "Test Post",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: "Test User",
commentCount: 5,
commentListUrl: nil,
hasEndorsed: true,
pinned: true,
closed: false,
following: true,
flagged: false,
abuseFlagged: false,
voted: true,
voteCount: 4,
createdAt: NSDate.stableTestDate(),
updatedAt: NSDate.stableTestDate(),
editableFields: nil,
read: false,
unreadCommentCount: 4,
responseCount: 0,
hasProfileImage: false,
imageURL: nil)
static let unendorsedComment = DiscussionComment(
commentID: "123",
parentID: "123",
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: true,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: false,
endorsedBy: nil,
endorsedByLabel: nil,
endorsedAt: nil,
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 0,
hasProfileImage: false,
imageURL: nil)
static let unendorsedComment1 = DiscussionComment(
commentID: "124",
parentID: "124",
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: true,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: false,
endorsedBy: nil,
endorsedByLabel: nil,
endorsedAt: nil,
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 5,
hasProfileImage: false,
imageURL: nil)
static let endorsedComment = DiscussionComment(
commentID: "125",
parentID: "125",
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: false,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: true,
endorsedBy: "Test Person 2",
endorsedByLabel: nil,
endorsedAt: NSDate.stableTestDate(),
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 0,
hasProfileImage: false,
imageURL: nil)
static let endorsedComment1 = DiscussionComment(
commentID: "126",
parentID: nil,
threadID: "345",
rawBody: "Lorem ipsum dolor sit amet",
renderedBody: "<p>Lorem ipsum dolor sit <a href=\"http://www.google.com/\">amet</a></p>",
author: "Test Person",
authorLabel: nil,
voted: true,
voteCount: 10,
createdAt: NSDate.stableTestDate(),
updatedAt: nil,
endorsed: false,
endorsedBy: nil,
endorsedByLabel: "Test Person 2",
endorsedAt: NSDate.stableTestDate(),
flagged: false,
abuseFlagged: false,
editableFields: nil,
childCount: 2,
hasProfileImage: false,
imageURL: nil)
static func unendorsedResponses()-> [DiscussionComment] {
return [unendorsedComment, unendorsedComment1]
}
static func endorsedResponses() -> [DiscussionComment] {
return [endorsedComment, endorsedComment1]
}
}
|
51269a3c28693d544bdb15b065b08857
| 29.017045 | 97 | 0.572781 | false | true | false | false |
kevintulod/CascadeKit-iOS
|
refs/heads/master
|
CascadeKit/CascadeKit/Cascade Controller/CascadeDividerView.swift
|
mit
|
1
|
//
// CascadeDividerView.swift
// CascadeKit
//
// Created by Kevin Tulod on 1/7/17.
// Copyright © 2017 Kevin Tulod. All rights reserved.
//
import UIKit
protocol CascadeDividerDelegate {
func divider(_ divider: CascadeDividerView, shouldTranslateToCenter center: CGPoint) -> Bool
func divider(_ divider: CascadeDividerView, didTranslateToCenter center: CGPoint)
}
/// Defines the behavior of the center divider between the master/detail views
class CascadeDividerView: UIView {
/// Sets the margin on either side of the divider that responds to touch
static let touchMargin = -CGFloat(10)
internal var lastCenter = CGPoint(x: 0, y: 0)
internal var delegate: CascadeDividerDelegate?
/// Overrides the point(inside:) function to allow the divider to respond to touches within `touchMargin` pixels on either side
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return bounds.insetBy(dx: CascadeDividerView.touchMargin, dy: 0).contains(point)
}
override func awakeFromNib() {
super.awakeFromNib()
lastCenter = center
setupPanGestures()
backgroundColor = .lightGray
}
/// Sets up the gesture recognizer for dragging
internal func setupPanGestures() {
let pan = UIPanGestureRecognizer(target: self, action: #selector(CascadeDividerView.detectPan(recognizer:)))
addGestureRecognizer(pan)
}
/// Responder for the UIPanGestureRecognizer that controls the dragging behavior of the divider
internal func detectPan(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .changed:
// Translate the center only by x
let translation = recognizer.translation(in: superview)
let newCenter = CGPoint(x: lastCenter.x + translation.x, y: lastCenter.y)
if let delegate = delegate, delegate.divider(self, shouldTranslateToCenter: newCenter) {
center = newCenter
delegate.divider(self, didTranslateToCenter: center)
}
case .ended:
lastCenter = center
default:
break
}
}
}
|
7b11816d5ad648d762dbf7536963735c
| 32.188406 | 131 | 0.650655 | false | false | false | false |
fgengine/quickly
|
refs/heads/master
|
Quickly/ViewControllers/Photos/PhotoItems/QImagePhotoItem.swift
|
mit
|
1
|
//
// Quickly
//
public class QImagePhotoItem : IQPhotoItem {
public var isNeedLoad: Bool {
get { return false }
}
public var isLoading: Bool {
get { return false }
}
public var size: CGSize {
return CGSize(width: self._image.width, height: self._image.height)
}
public var image: UIImage? {
get { return UIImage(cgImage: self._image) }
}
private var _observer: QObserver< IQPhotoItemObserver >
private var _image: CGImage
public static func photoItems(data: Data) -> [IQPhotoItem] {
guard let provider = CGDataProvider(data: data as CFData) else { return [] }
guard let imageSource = CGImageSourceCreateWithDataProvider(provider, nil) else { return [] }
var photos: [QImagePhotoItem] = []
for index in 0..<CGImageSourceGetCount(imageSource) {
guard let image = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { continue }
photos.append(QImagePhotoItem(image: image))
}
return photos
}
private init(image: CGImage) {
self._observer = QObserver< IQPhotoItemObserver >()
self._image = image
}
public func add(observer: IQPhotoItemObserver) {
self._observer.add(observer, priority: 0)
}
public func remove(observer: IQPhotoItemObserver) {
self._observer.remove(observer)
}
public func load() {
}
public func draw(context: CGContext, bounds: CGRect, scale: CGFloat) {
context.setFillColor(red: 1, green: 1, blue: 1, alpha: 1)
context.fill(bounds)
context.saveGState()
context.translateBy(x: 0, y: bounds.height)
context.scaleBy(x: 1, y: -1)
context.draw(self._image, in: bounds)
context.restoreGState()
}
}
|
4b58d464f6013d1cdd45acd119d2acc4
| 29.666667 | 104 | 0.616848 | false | false | false | false |
iHunterX/SocketIODemo
|
refs/heads/master
|
DemoSocketIO/Classes/RequiredViewController.swift
|
gpl-3.0
|
1
|
//
// RequiredViewController.swift
// DemoSocketIO
//
// Created by Đinh Xuân Lộc on 10/28/16.
// Copyright © 2016 Loc Dinh Xuan. All rights reserved.
//
import UIKit
class RequiredViewController: PAPermissionsViewController,PAPermissionsViewControllerDelegate {
let cameraCheck = PACameraPermissionsCheck()
let locationCheck = PALocationPermissionsCheck()
let microphoneCheck = PAMicrophonePermissionsCheck()
let photoLibraryCheck = PAPhotoLibraryPermissionsCheck()
lazy var notificationsCheck : PAPermissionsCheck = {
if #available(iOS 10.0, *) {
return PAUNNotificationPermissionsCheck()
} else {
return PANotificationsPermissionsCheck()
}
}()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = true
self.delegate = self
let permissions = [
PAPermissionsItem.itemForType(.location, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.microphone, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.photoLibrary, reason: PAPermissionDefaultReason)!,
PAPermissionsItem.itemForType(.notifications, reason: "Required to send you great updates")!,
PAPermissionsItem.itemForType(.camera, reason: PAPermissionDefaultReason)!]
let handlers = [
PAPermissionsType.location.rawValue: self.locationCheck,
PAPermissionsType.microphone.rawValue :self.microphoneCheck,
PAPermissionsType.photoLibrary.rawValue: self.photoLibraryCheck,
PAPermissionsType.camera.rawValue: self.cameraCheck,
PAPermissionsType.notifications.rawValue: self.notificationsCheck
]
self.setupData(permissions, handlers: handlers)
// Do any additional setup after loading the view.
self.tintColor = UIColor.white
self.backgroundImage = #imageLiteral(resourceName: "background")
self.useBlurBackground = false
self.titleText = "iSpam"
self.detailsText = "Please enable the following"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func permissionsViewControllerDidContinue(_ viewController: PAPermissionsViewController) {
if let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "MainController") as? UINavigationController {
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let presentingViewController: UIViewController! = self.presentingViewController
//
// self.dismiss(animated: false) {
// // go back to MainMenuView as the eyes of the user
// presentingViewController.dismiss(animated: false, completion: {
//// self.present(loginVC, animated: true, completion: nil)
// })
// }
loginVC.modalTransitionStyle = .crossDissolve
self.present(loginVC, animated: true, completion: nil)
}
}
/*
// 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.
}
*/
}
|
632444195f8cc78aa8496f0ace580d4f
| 39.213483 | 130 | 0.673931 | false | false | false | false |
pro1polaris/SwiftEssentials
|
refs/heads/master
|
SwiftEssentials/SwiftEssentials/_extensions_UIView_PositionContraints.swift
|
mit
|
1
|
//
// _extensions_UIView_Position_Constraints.swift
//
// Created by Paul Hopkins on 2017-03-05.
// Modified by Paul Hopkins on 2017-03-22.
// Copyright © 2017 Paul Hopkins. All rights reserved.
//
import UIKit
extension UIView {
// Apply CenterX Position Contraint (constant: 0)
func applyPositionConstraintCenterX(toitem: UIView) {
let centerXConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: toitem, attribute: .centerX, multiplier: 1, constant: 0)
toitem.addConstraint(centerXConstraint)
}
// Apply CenterY Position Constraint (constant: 0)
func applyPositionConstraintCenterY(toitem: UIView) {
let centerYConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: toitem, attribute: .centerY, multiplier: 1, constant: 0)
toitem.addConstraint(centerYConstraint)
}
// Apply All Four Position Constraints (constant: 0)
func applyPositionConstraintAll(toitem: UIView) {
self.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toitem, attribute: .top, multiplier: 1, constant: 0)
toitem.addConstraint(topConstraint)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toitem, attribute: .bottom, multiplier: 1, constant: 0)
toitem.addConstraint(bottomConstraint)
let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: 0)
toitem.addConstraint(leftConstraint)
let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: 0)
toitem.addConstraint(rightConstraint)
}
// Apply Top Position Constraint (constant: 0)
func applyPositionConstraintTop(toitem: UIView) {
let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: toitem, attribute: .top, multiplier: 1, constant: 0)
toitem.addConstraint(topConstraint)
}
// Apply Top Position Constraint (constant: Int)
func applyPositionConstraintTop_Constant(toitem: UIView, constant: Int) {
let topConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(topConstraint)
}
// Apply Bottom Position Constraint (constant: 0)
func applyPositionConstraintBottom(toitem: UIView) {
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: toitem, attribute: .bottom, multiplier: 1, constant: 0)
toitem.addConstraint(bottomConstraint)
}
// Apply Bottom Position Constraint (constant: Int)
func applyPositionConstraintBottom_Constant(toitem: UIView, constant: Int) {
let bottomConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(bottomConstraint)
}
// Apply Left Position Constraint (constant: 0)
func applyPositionConstraintLeft(toitem: UIView) {
let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: 0)
toitem.addConstraint(leftConstraint)
}
// Apply Left Position Constraint (constant: Int)
func applyPositionConstraintLeft_Constant(toitem: UIView, constant: Int) {
let leftConstraint = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: toitem, attribute: .left, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(leftConstraint)
}
// Apply Right Position Constraint (constant: 0)
func applyPositionConstraintRight(toitem: UIView) {
let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: 0)
toitem.addConstraint(rightConstraint)
}
//Apply Right Position Constraint (constant: Int)
func applyPositionConstraintRight_Constant(toitem: UIView, constant: Int) {
let rightConstraint = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: toitem, attribute: .right, multiplier: 1, constant: CGFloat(constant))
toitem.addConstraint(rightConstraint)
}
}
|
3ceb18618fda3c9294a4c47febd68233
| 53.482353 | 177 | 0.727057 | false | false | false | false |
zwaldowski/ParksAndRecreation
|
refs/heads/master
|
Latest/Keyboard Layout Guide/KeyboardLayoutGuide/KeyboardLayoutGuide.swift
|
mit
|
1
|
//
// KeyboardLayoutGuide.swift
// KeyboardLayoutGuide
//
// Created by Zachary Waldowski on 8/23/15.
// Copyright © 2015-2016. Licensed under MIT. Some rights reserved.
//
import UIKit
/// A keyboard layout guide may be used as an item in Auto Layout or for its
/// layout anchors.
public final class KeyboardLayoutGuide: UILayoutGuide {
private static let didUpdate = Notification.Name(rawValue: "KeyboardLayoutGuideDidUpdateNotification")
// MARK: Lifecycle
private let notificationCenter: NotificationCenter
private func commonInit() {
notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteUpdateKeyboard), name: .UIKeyboardDidChangeFrame, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteAncestorGuideUpdate), name: KeyboardLayoutGuide.didUpdate, object: nil)
notificationCenter.addObserver(self, selector: #selector(noteTextFieldDidEndEditing), name: .UITextFieldTextDidEndEditing, object: nil)
}
public required init?(coder aDecoder: NSCoder) {
self.notificationCenter = .default
super.init(coder: aDecoder)
commonInit()
}
fileprivate init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
commonInit()
}
override convenience init() {
self.init(notificationCenter: .default)
}
// MARK: Public API
/// If assigned, the `contentInsets` of the view will be adjusted to match
/// the keyboard insets.
///
/// It is not necessary to track the scroll view that is managed as the
/// primary view of a `UITableViewController` or
/// `UICollectionViewController`.
public weak var adjustContentInsetsInScrollView: UIScrollView?
// MARK: Actions
private var keyboardBottomConstraint: NSLayoutConstraint?
private var lastScrollViewInsetDelta: CGFloat = 0
private var currentAnimator: UIViewPropertyAnimator?
override public var owningView: UIView? {
didSet {
guard owningView !== oldValue else { return }
keyboardBottomConstraint?.isActive = false
keyboardBottomConstraint = nil
guard let view = owningView else { return }
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: trailingAnchor),
topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
view.safeAreaLayoutGuide.bottomAnchor.constraint(greaterThanOrEqualTo: bottomAnchor), {
let constraint = view.bottomAnchor.constraint(equalTo: bottomAnchor)
constraint.priority = UILayoutPriority(rawValue: 999.5)
self.keyboardBottomConstraint = constraint
return constraint
}()
])
}
}
private func update(for info: KeyboardInfo, in view: UIView, animatingWith animator: UIViewPropertyAnimator?) {
keyboardBottomConstraint?.constant = info.overlap(in: view)
if let animator = animator, !view.isEffectivelyDisappearing {
animator.addAnimations {
info.adjustForOverlap(in: self.adjustContentInsetsInScrollView, lastAppliedInset: &self.lastScrollViewInsetDelta)
view.layoutIfNeeded()
}
} else {
info.adjustForOverlap(in: adjustContentInsetsInScrollView, lastAppliedInset: &lastScrollViewInsetDelta)
}
}
// MARK: - Notifications
@objc
private func noteUpdateKeyboard(_ note: Notification) {
let info = KeyboardInfo(userInfo: note.userInfo)
guard let view = owningView else { return }
let animator = currentAnimator ?? {
UIView.performWithoutAnimation(view.layoutIfNeeded)
let animator = info.makeAnimator()
animator.addCompletion { [weak self] _ in
self?.currentAnimator = nil
}
self.currentAnimator = animator
return animator
}()
update(for: info, in: view, animatingWith: animator)
NotificationCenter.default.post(name: KeyboardLayoutGuide.didUpdate, object: self, userInfo: note.userInfo)
animator.startAnimation()
}
@objc
private func noteAncestorGuideUpdate(note: Notification) {
guard let view = owningView, let ancestor = note.object as? KeyboardLayoutGuide, let ancestorView = ancestor.owningView,
view !== ancestorView, view.isDescendant(of: ancestorView) else { return }
let info = KeyboardInfo(userInfo: note.userInfo)
update(for: info, in: view, animatingWith: ancestor.currentAnimator)
}
// <rdar://problem/30978412> UITextField contents animate in when layout performed during editing end
@objc
private func noteTextFieldDidEndEditing(_ note: Notification) {
guard let view = owningView, let textField = note.object as? UITextField,
view !== textField, textField.isDescendant(of: view), !view.isEffectivelyDisappearing else { return }
UIView.performWithoutAnimation(textField.layoutIfNeeded)
}
}
// MARK: - UIViewController
extension UIViewController {
private static var keyboardLayoutGuideKey = false
/// For unit testing purposes only.
@nonobjc
internal func makeKeyboardLayoutGuide(notificationCenter: NotificationCenter) -> KeyboardLayoutGuide {
assert(isViewLoaded, "This layout guide should not be accessed before the view is loaded.")
let guide = KeyboardLayoutGuide(notificationCenter: notificationCenter)
view.addLayoutGuide(guide)
return guide
}
/// A keyboard layout guide is a rectangle in the layout system representing
/// the area on screen not currently occupied by the keyboard; thus, it is a
/// simplified model for performing layout by avoiding the keyboard.
///
/// Normally, the guide is a rectangle matching the safe area of a view
/// controller's view. When the keyboard is active, its bottom contracts to
/// account for the keyboard. This change is animated alongside the keyboard
/// animation.
///
/// - seealso: KeyboardLayoutGuide
@nonobjc public var keyboardLayoutGuide: KeyboardLayoutGuide {
if let guide = objc_getAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey) as? KeyboardLayoutGuide {
return guide
}
let guide = makeKeyboardLayoutGuide(notificationCenter: .default)
objc_setAssociatedObject(self, &UIViewController.keyboardLayoutGuideKey, guide, .OBJC_ASSOCIATION_ASSIGN)
return guide
}
}
// MARK: -
private struct KeyboardInfo {
let userInfo: [AnyHashable: Any]?
func makeAnimator() -> UIViewPropertyAnimator {
let duration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval) ?? 0.25
return UIViewPropertyAnimator(duration: duration, timingParameters: UISpringTimingParameters())
}
func overlap(in view: UIView) -> CGFloat {
guard let endFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect,
view.canBeObscuredByKeyboard else { return 0 }
let intersection = view.convert(endFrame, from: UIScreen.main.coordinateSpace).intersection(view.bounds)
guard !intersection.isNull, intersection.maxY == view.bounds.maxY else { return 0 }
var height = intersection.height
if let scrollView = view as? UIScrollView, scrollView.contentInsetAdjustmentBehavior != .never {
height -= view.safeAreaInsets.bottom
}
return max(height, 0)
}
func adjustForOverlap(in scrollView: UIScrollView?, lastAppliedInset: inout CGFloat) {
guard let scrollView = scrollView else { return }
let newOverlap = overlap(in: scrollView)
let delta = newOverlap - lastAppliedInset
lastAppliedInset = newOverlap
scrollView.scrollIndicatorInsets.bottom += delta
scrollView.contentInset.bottom += delta
}
}
|
f7566d013cfcc608578962ea3a162622
| 37.99537 | 143 | 0.691915 | false | false | false | false |
longitachi/ZLPhotoBrowser
|
refs/heads/master
|
Sources/General/ZLImageNavController.swift
|
mit
|
1
|
//
// ZLImageNavController.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/18.
//
// Copyright (c) 2020 Long Zhang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Photos
class ZLImageNavController: UINavigationController {
var isSelectedOriginal: Bool = false
var arrSelectedModels: [ZLPhotoModel] = []
var selectImageBlock: (() -> Void)?
var cancelBlock: (() -> Void)?
deinit {
zl_debugPrint("ZLImageNavController deinit")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ZLPhotoUIConfiguration.default().statusBarStyle
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nil, bundle: nil)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
navigationBar.barStyle = .black
navigationBar.isTranslucent = true
modalPresentationStyle = .fullScreen
isNavigationBarHidden = true
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
54a8e9bf083d9153bcea8b36211d8a1b
| 33.28169 | 82 | 0.700493 | false | false | false | false |
PrajeetShrestha/imgurdemo
|
refs/heads/master
|
MobilabDemo/Globals/Utils.swift
|
apache-2.0
|
1
|
//
// Utils.swift
// MobilabDemo
//
// Created by [email protected] on 5/1/16.
// Copyright © 2016 Prajeet Shrestha. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
|
52675cb70a58e6eeb84989ddd49d214b
| 31.636364 | 116 | 0.599721 | false | false | false | false |
Randoramma/ImageSearcher
|
refs/heads/master
|
ImageSearcher/Models/RequestManager.swift
|
mit
|
1
|
//
// RequestManager.swift
// ImageSearcher
//
// Created by Randy McLain on 10/7/17.
// Copyright © 2017 Randy McLain. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
enum RequestError {
case GeneralError
case NoInternetConnectionError
}
/*
API Service class
1. Create struct containing public members required to use API
2. Create Singleton - service class should be singleton
3.
*/
class RequestManager {
static let sharedInstance = RequestManager()
private var pageForSearch: Int
private var pageForEditorsChoice: Int
private struct API {
/// the URL base for the API
static let baseURL = PrivateConstants.private_store_url
/// The API Key provided to consume the API
static let apiKey = PrivateConstants.private_pixabay_API_Key
}
// private initalizer
private init() {
self.pageForEditorsChoice = 1;
self.pageForSearch = 1;
}
/// Alamofire Service Methods
/// see https://github.com/Alamofire/Alamofire#parameter-encoding for options on request parameters.
func getImagesByName(nameToSearch name: String, completionHandler: @escaping (_ photos: [Photo]?, _ error: Error?) -> Void) {
let queryString = name.URLEncodedValue
let parameters: [String: Any] = ["key": API.apiKey,
"q": queryString,
"safesearch": true,
"page": pageForSearch]
// perform request and increment if request succeeds.
Alamofire.request(API.baseURL, parameters: parameters).validate().responseJSON { (response) in
switch(response.result) {
case .success(let value):
self.pageForSearch += 1
let json = JSON(value)
let photos = self.parseJsonForPhoto(json) // parse for objects
DispatchQueue.main.async(execute: {
completionHandler(photos, nil) // usually return objects on main queue.
})
case .failure(let error):
DispatchQueue.main.async(execute: {
completionHandler(nil, error)
print(error.localizedDescription)
})
}
}
}
func getEditorChoiceImages(completionHandler: @escaping (_ photos: [Photo]?, _ error: Error?) -> Void) {
let parameters: [String: Any] = ["key": API.apiKey,
"editors_choice": true,
"safesearch": true,
"page": pageForEditorsChoice]
// the fetch request and increment request variable if request succeeds.
Alamofire.request(API.baseURL, parameters: parameters).validate().responseJSON { (response) in
switch(response.result) {
case .success(let value):
self.pageForEditorsChoice += 1
let json = JSON(value)
let photos = self.parseJsonForPhoto(json) // parse for objects
DispatchQueue.main.async(execute: {
completionHandler(photos, nil) // usually return objects on main queue.
})
case .failure(let error):
DispatchQueue.main.async(execute: {
completionHandler(nil, error)
print(error.localizedDescription)
})
}
}
}
func getImagesByID(imageID id: String) {
let parameters: [String: Any] = ["key": API.apiKey, "id": id]
Alamofire.request(API.baseURL, parameters: parameters).responseJSON { (response) in
switch(response.result) {
case .success(let value):
print(value)
case .failure(let error):
print(error.localizedDescription)
}
}
}
/*
Automagically caches each image recieved from network requests to improve responsiveness. Prior to making network request AlamofireImage checks if the image was requested previously and if so pulls that image from the cache. Only works while connecetd to network.
*/
func getImageByURL(urlOfImage url: String, completionHandler: @escaping (_ image: UIImage?, _ error: Error?) ->Void) {
Alamofire.request(url).responseImage { (response) in
switch(response.result) {
case .success(let value):
completionHandler(value, nil)
case .failure(let error):
print("the error is \(error)")
}
}
}
fileprivate func parseJsonForPhoto(_ json: JSON)->[Photo] {
var photoArray = [Photo]()
guard let hits = json["hits"].array else {
return photoArray
}
for item in hits { // ensure your keys are spelled and typed correctly. (cmnd+p from results)
if let url = item["webformatURL"].string,
let likes = item["likes"].int,
let favortites = item["favorites"].int {
let photo = Photo(theUrl: url, theLikes: likes, theFavs: favortites)
photoArray.append(photo)
}
}
return photoArray
}
}
public extension String {
/* For performance, I've replaced the char constants with integers, as char constants don't work in Swift.
https://stackoverflow.com/questions/3423545/objective-c-iphone-percent-encode-a-string/20271177#20271177
*/
var URLEncodedValue: String {
let output = NSMutableString()
guard let source = self.cString(using: String.Encoding.utf8) else {
return self
}
let sourceLen = source.count
var i = 0
while i < sourceLen - 1 {
let thisChar = source[i]
if thisChar == 32 {
output.append("+")
} else if thisChar == 46 || thisChar == 45 || thisChar == 95 || thisChar == 126 ||
(thisChar >= 97 && thisChar <= 122) ||
(thisChar >= 65 && thisChar <= 90) ||
(thisChar >= 48 && thisChar <= 57) {
output.appendFormat("%c", thisChar)
} else {
output.appendFormat("%%%02X", thisChar)
}
i += 1
}
return output as String
}
}
/*
Error handling in Swift
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
*/
/*
hits = (
{
comments = 27;
downloads = 113;
favorites = 9;
id = 2802838;
imageHeight = 2929;
imageWidth = 2930;
likes = 31;
pageURL = "https://";
previewHeight = 149;
previewURL = "https:___.jpg";
previewWidth = 150;
tags = "cow, beef, animal";
type = photo;
user = Couleur;
userImageURL = "https://____.jpg";
"user_id" = 1195798;
views = 388;
webformatHeight = 639;
webformatURL = "https://____.jpg";
webformatWidth = 640;
},
*/
|
10095c55316169bfe457267866161594
| 34.193069 | 271 | 0.570263 | false | false | false | false |
kylef/Mockingdrive
|
refs/heads/master
|
Pods/WebLinking/WebLinking/WebLinking.swift
|
bsd-2-clause
|
4
|
//
// WebLinking.swift
// WebLinking
//
// Created by Kyle Fuller on 20/01/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import Foundation
/// A structure representing a RFC 5988 link.
public struct Link: Equatable, Hashable {
/// The URI for the link
public let uri:String
/// The parameters for the link
public let parameters:[String:String]
/// Initialize a Link with a given uri and parameters
public init(uri:String, parameters:[String:String]? = nil) {
self.uri = uri
self.parameters = parameters ?? [:]
}
/// Returns the hash value
public var hashValue:Int {
return uri.hashValue
}
/// Relation type of the Link.
public var relationType:String? {
return parameters["rel"]
}
/// Reverse relation of the Link.
public var reverseRelationType:String? {
return parameters["rev"]
}
/// A hint of what the content type for the link may be.
public var type:String? {
return parameters["type"]
}
}
/// Returns whether two Link's are equivalent
public func ==(lhs:Link, rhs:Link) -> Bool {
return lhs.uri == rhs.uri && lhs.parameters == rhs.parameters
}
// MARK: HTML Element Conversion
/// An extension to Link to provide conversion to a HTML element
extension Link {
/// Encode the link into a HTML element
public var html:String {
let components = parameters.map { (key, value) in
"\(key)=\"\(value)\""
} + ["href=\"\(uri)\""]
let elements = components.joinWithSeparator(" ")
return "<link \(elements) />"
}
}
// MARK: Header link conversion
/// An extension to Link to provide conversion to and from a HTTP "Link" header
extension Link {
/// Encode the link into a header
public var header:String {
let components = ["<\(uri)>"] + parameters.map { (key, value) in
"\(key)=\"\(value)\""
}
return components.joinWithSeparator("; ")
}
/*** Initialize a Link with a HTTP Link header
- parameter header: A HTTP Link Header
*/
public init(header:String) {
let (uri, parametersString) = takeFirst(separateBy(";")(input: header))
let parameters = Array(Array(parametersString.map(split("="))).map { parameter in
[parameter.0: trim("\"", rhs: "\"")(input: parameter.1)]
})
self.uri = trim("<", rhs: ">")(input: uri)
self.parameters = parameters.reduce([:], combine: +)
}
}
/*** Parses a Web Linking (RFC5988) header into an array of Links
- parameter header: RFC5988 link header. For example `<?page=3>; rel=\"next\", <?page=1>; rel=\"prev\"`
:return: An array of Links
*/
public func parseLinkHeader(header:String) -> [Link] {
return separateBy(",")(input: header).map { string in
return Link(header: string)
}
}
/// An extension to NSHTTPURLResponse adding a links property
extension NSHTTPURLResponse {
/// Parses the links on the response `Link` header
public var links:[Link] {
if let linkHeader = allHeaderFields["Link"] as? String {
return parseLinkHeader(linkHeader).map { link in
var uri = link.uri
/// Handle relative URIs
if let baseURL = self.URL, URL = NSURL(string: uri, relativeToURL: baseURL) {
uri = URL.absoluteString
}
return Link(uri: uri, parameters: link.parameters)
}
}
return []
}
/// Finds a link which has matching parameters
public func findLink(parameters:[String:String]) -> Link? {
for link in links {
if link.parameters ~= parameters {
return link
}
}
return nil
}
/// Find a link for the relation
public func findLink(relation relation:String) -> Link? {
return findLink(["rel": relation])
}
}
/// MARK: Private methods (used by link header conversion)
// Merge two dictionaries together
func +<K,V>(lhs:Dictionary<K,V>, rhs:Dictionary<K,V>) -> Dictionary<K,V> {
var dictionary = [K:V]()
for (key, value) in rhs {
dictionary[key] = value
}
for (key, value) in lhs {
dictionary[key] = value
}
return dictionary
}
/// LHS contains all the keys and values from RHS
func ~=(lhs:[String:String], rhs:[String:String]) -> Bool {
for (key, value) in rhs {
if lhs[key] != value {
return false
}
}
return true
}
// Separate a trim a string by a separator
func separateBy(separator:String)(input:String) -> [String] {
return input.componentsSeparatedByString(separator).map {
$0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
// Split a string by a separator into two components
func split(separator:String)(input:String) -> (String, String) {
let range = input.rangeOfString(separator, options: NSStringCompareOptions(rawValue: 0), range: nil, locale: nil)
if let range = range {
let lhs = input.substringToIndex(range.startIndex)
let rhs = input.substringFromIndex(range.endIndex)
return (lhs, rhs)
}
return (input, "")
}
// Separate the first element in an array from the rest
func takeFirst(input:[String]) -> (String, ArraySlice<String>) {
if let first = input.first {
let items = input[input.startIndex.successor() ..< input.endIndex]
return (first, items)
}
return ("", [])
}
// Trim a prefix and suffix from a string
func trim(lhs:Character, rhs:Character)(input:String) -> String {
if input.hasPrefix("\(lhs)") && input.hasSuffix("\(rhs)") {
return input[input.startIndex.successor()..<input.endIndex.predecessor()]
}
return input
}
|
db0da206a67260e1a2866ab767d40d08
| 25.719212 | 115 | 0.656895 | false | false | false | false |
icecoffin/GlossLite
|
refs/heads/master
|
GlossLite/Views/WordList/WordListCell.swift
|
mit
|
1
|
//
// WordListCell.swift
// GlossLite
//
// Created by Daniel on 25/09/16.
// Copyright © 2016 icecoffin. All rights reserved.
//
import UIKit
class WordListCell: UITableViewCell {
private let wordTextLabel = UILabel()
private let definitionLabel = UILabel()
static var reuseIdentifier: String {
return String(describing: WordListCell.self)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
addWordTextLabel()
addDefinitionLabel()
}
private func addWordTextLabel() {
contentView.addSubview(wordTextLabel)
wordTextLabel.snp.makeConstraints { make in
make.top.equalTo(contentView.snp.topMargin)
make.leading.equalTo(contentView.snp.leadingMargin)
make.trailing.equalTo(contentView.snp.trailingMargin)
}
wordTextLabel.font = Fonts.openSans(size: 20)
}
private func addDefinitionLabel() {
contentView.addSubview(definitionLabel)
definitionLabel.snp.makeConstraints { make in
make.top.equalTo(wordTextLabel.snp.bottom)
make.leading.equalTo(contentView.snp.leadingMargin)
make.trailing.equalTo(contentView.snp.trailingMargin)
make.bottom.equalTo(contentView.snp.bottomMargin)
}
definitionLabel.font = Fonts.openSansItalic(size: 14)
definitionLabel.textColor = UIColor.gray
}
func configure(with viewModel: WordListCellViewModel) {
wordTextLabel.text = viewModel.text
definitionLabel.text = viewModel.definition
}
}
|
a569c572dc810c06a5cbbc3f96d55eb6
| 25.854839 | 72 | 0.729129 | false | false | false | false |
hironytic/XMLPullitic
|
refs/heads/master
|
Sources/XMLPullParser.swift
|
mit
|
1
|
//
// XMLPullParser.swift
// XMLPullitic
//
// Copyright (c) 2016-2019 Hironori Ichimiya <[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 Foundation
public class XMLPullParser {
private var internalParser: InternalXMLParser
public convenience init?(contentsOfURL url: URL) {
guard let parser = XMLParser(contentsOf:url) else { return nil }
self.init(xmlParser: parser)
}
public convenience init(data: Data) {
self.init(xmlParser: XMLParser(data: data))
}
public convenience init(stream: InputStream) {
self.init(xmlParser: XMLParser(stream: stream))
}
public convenience init?(string: String) {
guard let data = (string as NSString).data(using: String.Encoding.utf8.rawValue) else { return nil }
self.init(data: data)
}
init(xmlParser: XMLParser) {
self.internalParser = InternalXMLParser(xmlParser: xmlParser)
}
deinit {
abortParsing()
}
public var shouldProcessNamespaces: Bool {
get {
return self.internalParser.xmlParser.shouldProcessNamespaces
}
set(value) {
self.internalParser.xmlParser.shouldProcessNamespaces = value
}
}
public var lineNumber: Int {
get {
return self.internalParser.xmlParser.lineNumber
}
}
public var columnNumber: Int {
get {
return self.internalParser.xmlParser.columnNumber
}
}
public var depth: Int {
get {
return self.internalParser.depth
}
}
public func next() throws -> XMLEvent {
return try internalParser.requestEvent()
}
public func abortParsing() {
internalParser.abortParsing()
}
}
// MARK: -
@objc private class InternalXMLParser: NSObject, XMLParserDelegate {
class LockCondition {
static let Requested: Int = 0
static let Provided: Int = 1
}
enum State {
case notStarted
case parsing
case aborted
case ended
}
enum EventOrError {
case event(XMLEvent)
case error(Error)
}
let xmlParser: XMLParser
let lock: NSConditionLock
var currentEventOrError: EventOrError
var state: State
var depth: Int
var accumulatedChars: String?
// MARK: methods called on original thread
init(xmlParser: XMLParser) {
self.xmlParser = xmlParser
self.lock = NSConditionLock(condition: LockCondition.Requested)
self.currentEventOrError = EventOrError.event(XMLEvent.startDocument)
self.state = .notStarted
self.depth = 0
super.init()
}
func abortParsing() {
guard state == .parsing else { return }
state = .aborted
// awake wating parser
lock.unlock(withCondition: LockCondition.Requested)
}
func requestEvent() throws -> XMLEvent {
switch state {
case .notStarted:
state = .parsing
xmlParser.delegate = self
DispatchQueue.global(qos: .default).async {
self.lock.lock(whenCondition: LockCondition.Requested)
self.xmlParser.parse()
}
case .parsing:
lock.unlock(withCondition: LockCondition.Requested)
case .aborted:
return XMLEvent.endDocument
case .ended:
return XMLEvent.endDocument
}
lock.lock(whenCondition: LockCondition.Provided)
switch currentEventOrError {
case .error(let error):
state = .ended
lock.unlock()
throw error
case .event(XMLEvent.endDocument):
state = .ended
lock.unlock()
return XMLEvent.endDocument
case .event(let event):
return event
}
}
// MARK: methods called on background thread
func provide(_ eventOrError: EventOrError) {
if let chars = accumulatedChars {
accumulatedChars = nil
provide(.event(.characters(chars)))
waitForNextRequest()
}
if (state == .parsing) {
currentEventOrError = eventOrError
lock.unlock(withCondition: LockCondition.Provided)
}
}
func waitForNextRequest() {
guard state == .parsing else {
if (state == .aborted && xmlParser.delegate != nil) {
xmlParser.delegate = nil
xmlParser.abortParsing()
}
return
}
lock.lock(whenCondition: LockCondition.Requested)
if (state == .aborted) {
xmlParser.delegate = nil
xmlParser.abortParsing()
lock.unlock()
}
}
func accumulate(characters chars: String) {
accumulatedChars = (accumulatedChars ?? "") + chars
}
@objc func parserDidStartDocument(_ parser: XMLParser) {
provide(.event(.startDocument))
waitForNextRequest()
}
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
depth += 1
let element = XMLElement(name: elementName, namespaceURI: namespaceURI, qualifiedName: qName, attributes: attributeDict)
provide(.event(.startElement(name: elementName, namespaceURI: namespaceURI, element: element)))
waitForNextRequest()
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
provide(.event(.endElement(name: elementName, namespaceURI: namespaceURI)))
waitForNextRequest()
depth -= 1
}
@objc func parser(_ parser: XMLParser, foundCharacters string: String) {
accumulate(characters: string)
}
@objc func parserDidEndDocument(_ parser: XMLParser) {
provide(.event(.endDocument))
}
@objc func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
provide(.error(XMLPullParserError.parseError(innerError: parseError)))
}
@objc func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
if let text = NSString(data: CDATABlock, encoding: String.Encoding.utf8.rawValue) {
accumulate(characters: text as String)
}
}
}
|
b3fd117f91c8619a60b17b472b53da68
| 29.894309 | 179 | 0.621711 | false | false | false | false |
powerytg/Accented
|
refs/heads/master
|
Accented/Core/API/Requests/SearchPhotosRequest.swift
|
mit
|
1
|
//
// SearchPhotosRequest.swift
// Accented
//
// Created by Tiangong You on 5/21/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class SearchPhotosRequest: APIRequest {
private var keyword : String?
private var tag : String?
private var page : Int
private var sorting : PhotoSearchSortingOptions
init(keyword : String, page : Int = 1, sort : PhotoSearchSortingOptions, params : [String : String], success : SuccessAction?, failure : FailureAction?) {
self.keyword = keyword
self.page = page
self.sorting = sort
super.init(success: success, failure: failure)
cacheKey = "search_photos/\(keyword)/\(page)"
url = "\(APIRequest.baseUrl)photos/search"
parameters = params
parameters[RequestParameters.term] = keyword
parameters[RequestParameters.page] = String(page)
parameters[RequestParameters.sort] = sort.rawValue
parameters[RequestParameters.includeStates] = "1"
if params[RequestParameters.imageSize] == nil {
parameters[RequestParameters.imageSize] = APIRequest.defaultImageSizesForStream.map({ (size) -> String in
return size.rawValue
}).joined(separator: ",")
}
// By default, exclude node content
parameters[RequestParameters.excludeNude] = "1"
if params[RequestParameters.exclude] == nil {
// Apply default filters
parameters[RequestParameters.exclude] = APIRequest.defaultExcludedCategories.joined(separator: ",")
}
}
init(tag : String, page : Int = 1, sort : PhotoSearchSortingOptions, params : [String : String], success : SuccessAction?, failure : FailureAction?) {
self.tag = tag
self.page = page
self.sorting = sort
super.init(success: success, failure: failure)
cacheKey = "search_photos/\(tag)/\(page)"
url = "\(APIRequest.baseUrl)photos/search"
parameters = params
parameters[RequestParameters.tag] = tag
parameters[RequestParameters.page] = String(page)
parameters[RequestParameters.sort] = sort.rawValue
parameters[RequestParameters.includeStates] = "1"
if params[RequestParameters.imageSize] == nil {
parameters[RequestParameters.imageSize] = APIRequest.defaultImageSizesForStream.map({ (size) -> String in
return size.rawValue
}).joined(separator: ",")
}
// By default, exclude node content
parameters[RequestParameters.excludeNude] = "1"
if params[RequestParameters.exclude] == nil {
// Apply default filters
parameters[RequestParameters.exclude] = APIRequest.defaultExcludedCategories.joined(separator: ",")
}
}
override func handleSuccess(data: Data, response: HTTPURLResponse?) {
super.handleSuccess(data: data, response: response)
var userInfo : [String : Any] = [RequestParameters.feature : StreamType.Search.rawValue,
RequestParameters.page : page,
RequestParameters.response : data,
RequestParameters.sort : sorting]
if keyword != nil {
userInfo[RequestParameters.term] = keyword!
} else if tag != nil {
userInfo[RequestParameters.tag] = tag!
}
NotificationCenter.default.post(name: APIEvents.streamPhotosDidReturn, object: nil, userInfo: userInfo)
if let success = successAction {
success()
}
}
override func handleFailure(_ error: Error) {
super.handleFailure(error)
let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription]
NotificationCenter.default.post(name: APIEvents.streamPhotosFailedReturn, object: nil, userInfo: userInfo)
if let failure = failureAction {
failure(error.localizedDescription)
}
}
}
|
799ada2adb0881339afc46630f221812
| 37.703704 | 158 | 0.612679 | false | false | false | false |
jyxia/CrowdFood-iOS
|
refs/heads/master
|
CrowdFood/HomeViewController.swift
|
mit
|
1
|
//
// HomeViewController.swift
// CrowdFood
//
// Created by Jinyue Xia on 10/10/15.
// Copyright © 2015 Jinyue Xia. All rights reserved.
//
import UIKit
import VideoSplash
class HomeViewController: VideoSplashViewController, VideoPlayerEventDelegate {
@IBOutlet weak var enterBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("restaurant", ofType: "mp4")!)
self.videoFrame = view.frame
self.fillMode = .ResizeAspectFill
self.alwaysRepeat = true
self.sound = true
self.startTime = 0.0
self.alpha = 0.7
self.backgroundColor = UIColor.blackColor()
self.contentURL = url
self.sound = false
self.eventDelegate = self
enterBtn.backgroundColor = UIColor.clearColor()
enterBtn.layer.cornerRadius = 5
enterBtn.layer.borderWidth = 1
enterBtn.layer.borderColor = UIColor.greenColor().CGColor
let text = UILabel(frame: CGRect(x: 0.0, y: 100.0, width: 320.0, height: 100.0))
text.font = UIFont(name: "Museo500-Regular", size: 40)
text.textAlignment = NSTextAlignment.Center
text.textColor = UIColor.whiteColor()
text.text = "Crowd Food"
view.addSubview(text)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
self.navigationController?.setToolbarHidden(false, animated: true)
}
@IBAction func tapEnter(sender: UIButton) {
self.performSegueWithIdentifier("HomeToMap", sender: self)
}
func videoDidEnd() {
self.performSegueWithIdentifier("HomeToMap", sender: self)
}
}
|
fe3f9cfb93e2a500cc04ad34d55a52a1
| 27.301587 | 104 | 0.704265 | false | false | false | false |
ijoshsmith/swift-morse-code
|
refs/heads/master
|
MorseCode/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// MorseCode
//
// Created by Joshua Smith on 7/8/16.
// Copyright © 2016 iJoshSmith. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var blinkingView: UIView!
@IBOutlet weak var encodedMessageTextView: UITextView!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var transmitMessageButton: UIButton!
private var morseTransmitter: MorseTransmitter!
private struct BlinkingViewColors {
static let on = UIColor.greenColor()
static let off = UIColor.lightGrayColor()
}
override func viewDidLoad() {
super.viewDidLoad()
morseTransmitter = MorseTransmitter(blinkingView: blinkingView,
onColor: BlinkingViewColors.on,
offColor: BlinkingViewColors.off)
blinkingView.backgroundColor = BlinkingViewColors.off
blinkingView.layer.cornerRadius = blinkingView.frame.width / 2.0;
}
@IBAction func handleTransmitMessageButton(sender: AnyObject) {
if let message = messageTextField.text where message.isEmpty == false {
transmit(message)
}
}
private func transmit(message: String) {
let morseEncoder = MorseEncoder(codingSystem: .InternationalMorseCode)
if let encodedMessage = morseEncoder.encode(message: message) {
showMorseCodeTextFor(encodedMessage)
beginTransmitting(encodedMessage)
}
else {
encodedMessageTextView.text = "Unable to encode at least one character in message."
}
}
private func showMorseCodeTextFor(encodedMessage: EncodedMessage) {
encodedMessageTextView.text = createMorseCodeText(from: encodedMessage)
encodedMessageTextView.font = UIFont(name: "Menlo", size: 16)
}
private func createMorseCodeText(from encodedMessage: EncodedMessage) -> String {
let transformation = MorseTransformation(
dot: ".",
dash: "-",
markSeparator: "",
symbolSeparator: " ",
termSeparator: "\n")
let characters = transformation.apply(to: encodedMessage)
return characters.joinWithSeparator("")
}
private func beginTransmitting(encodedMessage: EncodedMessage) {
transmitMessageButton.enabled = false
morseTransmitter.startTransmitting(encodedMessage: encodedMessage) { [weak self] in
self?.transmitMessageButton.enabled = true
}
}
}
|
575957237960991dc3305169c98dd38a
| 34.266667 | 95 | 0.641588 | false | false | false | false |
seanwoodward/IBAnimatable
|
refs/heads/master
|
IBAnimatable/SystemPageAnimator.swift
|
mit
|
1
|
//
// Created by Tom Baranes on 28/03/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class SystemPageAnimator: NSObject, AnimatedTransitioning {
// MARK: - AnimatorProtocol
public var transitionAnimationType: TransitionAnimationType
public var transitionDuration: Duration = defaultTransitionDuration
public var reverseAnimationType: TransitionAnimationType?
public var interactiveGestureType: InteractiveGestureType?
// MARK: - private
private var type: TransitionPageType
public init(type: TransitionPageType, transitionDuration: Duration) {
self.transitionDuration = transitionDuration
self.type = type
switch type {
case .Curl:
self.transitionAnimationType = .SystemPage(type: .Curl)
self.reverseAnimationType = .SystemPage(type: .UnCurl)
case .UnCurl:
self.transitionAnimationType = .SystemPage(type: .UnCurl)
self.reverseAnimationType = .SystemPage(type: .Curl)
}
super.init()
}
}
extension SystemPageAnimator: UIViewControllerAnimatedTransitioning {
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return retrieveTransitionDuration(transitionContext)
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
switch self.type {
case .Curl:
animateWithCATransition(transitionContext, type: SystemTransitionType.PageCurl, subtype: nil)
case .UnCurl:
animateWithCATransition(transitionContext, type: SystemTransitionType.PageUnCurl, subtype: nil)
}
}
}
|
0517acd8aea1e1aea2097fe43b4b6a63
| 32.75 | 110 | 0.760494 | false | false | false | false |
Somnibyte/MLKit
|
refs/heads/master
|
Example/MLKit/GameScene.swift
|
mit
|
1
|
//
// GameScene.swift
// FlappyBird
//
// Created by Nate Murray on 6/2/14.
// Copyright (c) 2014 Fullstack.io. All rights reserved.
//
import SpriteKit
import MachineLearningKit
import Upsurge
class GameScene: SKScene, SKPhysicsContactDelegate {
// ADDITIONS
/// Container for our Flappy Birds
var flappyBirdGenerationContainer: [FlappyGenome]?
/// The current genome
var currentBird: FlappyGenome?
/// The current flappy bird of the current generation (see 'generationCounter' variable)
var currentFlappy: Int = 0
/// Variable used to count the number of generations that have passed
var generationCounter = 1
/// Variable to keep track of the current time (this is used to determine fitness later)
var currentTimeForFlappyBird = NSDate()
/// The red square (our goal area)
var goalArea: SKShapeNode!
/// The pipe that is in front of the bird
var currentPipe: Int = 0
/// The fitness of the best bird
var maxFitness: Float = 0
/// The best bird (from any generation)
var maxBird: FlappyGenome?
/// The best birds from the previous generation
var lastBestGen: [FlappyGenome] = []
/// SKLabel
var generationLabel: SKLabelNode!
var fitnessLabel: SKLabelNode!
let groundTexture = SKTexture(imageNamed: "land")
/// Best score (regardless of generation)
var bestScore: Int = 0
/// Label that displays the best score (bestScore attribute)
var bestScoreLabel: SKLabelNode!
// END of ADDITIONS
let verticalPipeGap = 150.0
var bird: SKSpriteNode!
var skyColor: SKColor!
var pipeTextureUp: SKTexture!
var pipeTextureDown: SKTexture!
var movePipesAndRemove: SKAction!
var moving: SKNode!
var pipes: SKNode!
var canRestart = Bool()
var scoreLabelNode: SKLabelNode!
var score = NSInteger()
let birdCategory: UInt32 = 1 << 0
let worldCategory: UInt32 = 1 << 1
let pipeCategory: UInt32 = 1 << 2
let scoreCategory: UInt32 = 1 << 3
override func didMove(to view: SKView) {
canRestart = false
// setup physics
self.physicsWorld.gravity = CGVector( dx: 0.0, dy: -5.0 )
self.physicsWorld.contactDelegate = self
// setup background color
skyColor = SKColor(red: 81.0/255.0, green: 192.0/255.0, blue: 201.0/255.0, alpha: 1.0)
self.backgroundColor = skyColor
moving = SKNode()
self.addChild(moving)
pipes = SKNode()
moving.addChild(pipes)
// ground
groundTexture.filteringMode = .nearest // shorter form for SKTextureFilteringMode.Nearest
let moveGroundSprite = SKAction.moveBy(x: -groundTexture.size().width * 2.0, y: 0, duration: TimeInterval(0.02 * groundTexture.size().width * 2.0))
let resetGroundSprite = SKAction.moveBy(x: groundTexture.size().width * 2.0, y: 0, duration: 0.0)
let moveGroundSpritesForever = SKAction.repeatForever(SKAction.sequence([moveGroundSprite, resetGroundSprite]))
for i in 0 ..< 2 + Int(self.frame.size.width / ( groundTexture.size().width * 2 )) {
let i = CGFloat(i)
let sprite = SKSpriteNode(texture: groundTexture)
sprite.setScale(2.0)
sprite.position = CGPoint(x: i * sprite.size.width, y: sprite.size.height / 2.0)
sprite.run(moveGroundSpritesForever)
moving.addChild(sprite)
}
// skyline
let skyTexture = SKTexture(imageNamed: "sky")
skyTexture.filteringMode = .nearest
let moveSkySprite = SKAction.moveBy(x: -skyTexture.size().width * 2.0, y: 0, duration: TimeInterval(0.1 * skyTexture.size().width * 2.0))
let resetSkySprite = SKAction.moveBy(x: skyTexture.size().width * 2.0, y: 0, duration: 0.0)
let moveSkySpritesForever = SKAction.repeatForever(SKAction.sequence([moveSkySprite, resetSkySprite]))
for i in 0 ..< 2 + Int(self.frame.size.width / ( skyTexture.size().width * 2 )) {
let i = CGFloat(i)
let sprite = SKSpriteNode(texture: skyTexture)
sprite.setScale(2.0)
sprite.zPosition = -20
sprite.position = CGPoint(x: i * sprite.size.width, y: sprite.size.height / 2.0 + groundTexture.size().height * 2.0)
sprite.run(moveSkySpritesForever)
moving.addChild(sprite)
}
// create the pipes textures
pipeTextureUp = SKTexture(imageNamed: "PipeUp")
pipeTextureUp.filteringMode = .nearest
pipeTextureDown = SKTexture(imageNamed: "PipeDown")
pipeTextureDown.filteringMode = .nearest
// create the pipes movement actions
let distanceToMove = CGFloat(self.frame.size.width + 2.0 * pipeTextureUp.size().width)
let movePipes = SKAction.moveBy(x: -distanceToMove, y:0.0, duration:TimeInterval(0.01 * distanceToMove))
let removePipes = SKAction.removeFromParent()
movePipesAndRemove = SKAction.sequence([movePipes, removePipes])
// spawn the pipes
let spawn = SKAction.run(spawnPipes)
let delay = SKAction.wait(forDuration: TimeInterval(2.0))
let spawnThenDelay = SKAction.sequence([spawn, delay])
let spawnThenDelayForever = SKAction.repeatForever(spawnThenDelay)
self.run(spawnThenDelayForever)
// setup our bird
let birdTexture1 = SKTexture(imageNamed: "bird-01")
birdTexture1.filteringMode = .nearest
let birdTexture2 = SKTexture(imageNamed: "bird-02")
birdTexture2.filteringMode = .nearest
let anim = SKAction.animate(with: [birdTexture1, birdTexture2], timePerFrame: 0.2)
let flap = SKAction.repeatForever(anim)
bird = SKSpriteNode(texture: birdTexture1)
bird.setScale(2.0)
bird.position = CGPoint(x: self.frame.size.width * 0.35, y:self.frame.size.height * 0.6)
bird.run(flap)
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height / 2.0)
bird.physicsBody?.isDynamic = true
bird.physicsBody?.allowsRotation = false
bird.physicsBody?.categoryBitMask = birdCategory
bird.physicsBody?.collisionBitMask = worldCategory | pipeCategory
bird.physicsBody?.contactTestBitMask = worldCategory | pipeCategory
self.addChild(bird)
// create the ground
let ground = SKNode()
ground.position = CGPoint(x: 0, y: groundTexture.size().height)
ground.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.frame.size.width, height: groundTexture.size().height * 2.0))
ground.physicsBody?.isDynamic = false
ground.physicsBody?.categoryBitMask = worldCategory
self.addChild(ground)
// Initialize label and create a label which holds the score
score = 0
scoreLabelNode = SKLabelNode(fontNamed:"MarkerFelt-Wide")
scoreLabelNode.position = CGPoint( x: self.frame.midX, y: 3 * self.frame.size.height / 4 )
scoreLabelNode.zPosition = 100
scoreLabelNode.text = String(score)
self.addChild(scoreLabelNode)
bestScore = 0
bestScoreLabel = SKLabelNode(fontNamed:"MarkerFelt-Wide")
bestScoreLabel.position = CGPoint( x: self.frame.midX - 120.0, y: 3 * self.frame.size.height / 4 + 110.0 )
bestScoreLabel.zPosition = 100
bestScoreLabel.text = "bestScore: \(self.bestScore)"
self.addChild(bestScoreLabel)
generationLabel = SKLabelNode(fontNamed:"MarkerFelt-Wide")
generationLabel.position = CGPoint( x: self.frame.midX - 150.0, y: 3 * self.frame.size.height / 4 + 140.0 )
generationLabel.zPosition = 100
generationLabel.text = "Gen: 1"
self.addChild(generationLabel)
fitnessLabel = SKLabelNode(fontNamed:"MarkerFelt-Wide")
fitnessLabel.position = CGPoint( x: self.frame.midX + 110.0, y: 3 * self.frame.size.height / 4 + 140.0 )
fitnessLabel.zPosition = 100
fitnessLabel.text = "Fitness: 0"
self.addChild(fitnessLabel)
// Set the current bird
if let generation = flappyBirdGenerationContainer {
currentBird = generation[currentFlappy]
}
}
func spawnPipes() {
let pipePair = SKNode()
pipePair.position = CGPoint( x: self.frame.size.width + pipeTextureUp.size().width * 2, y: 0 )
pipePair.zPosition = -10
let height = UInt32( self.frame.size.height / 4)
let y = Double(arc4random_uniform(height) + height)
let pipeDown = SKSpriteNode(texture: pipeTextureDown)
pipeDown.name = "DOWN"
pipeDown.setScale(2.0)
pipeDown.position = CGPoint(x: 0.0, y: y + Double(pipeDown.size.height) + verticalPipeGap)
pipeDown.physicsBody = SKPhysicsBody(rectangleOf: pipeDown.size)
pipeDown.physicsBody?.isDynamic = false
pipeDown.physicsBody?.categoryBitMask = pipeCategory
pipeDown.physicsBody?.contactTestBitMask = birdCategory
pipePair.addChild(pipeDown)
let pipeUp = SKSpriteNode(texture: pipeTextureUp)
pipeUp.setScale(2.0)
pipeUp.position = CGPoint(x: 0.0, y: y)
pipeUp.physicsBody = SKPhysicsBody(rectangleOf: pipeUp.size)
pipeUp.physicsBody?.isDynamic = false
pipeUp.physicsBody?.categoryBitMask = pipeCategory
pipeUp.physicsBody?.contactTestBitMask = birdCategory
// ADDITIONS
goalArea = SKShapeNode(rectOf: CGSize(width: 10, height: 10))
goalArea.name = "GOAL"
goalArea.fillColor = SKColor.red
goalArea.position = pipeUp.position
goalArea.position.y += 250
// END of ADDITIONS
pipePair.addChild(pipeUp)
pipePair.addChild(goalArea)
let contactNode = SKNode()
contactNode.position = CGPoint( x: pipeDown.size.width + bird.size.width / 2, y: self.frame.midY )
contactNode.physicsBody = SKPhysicsBody(rectangleOf: CGSize( width: pipeUp.size.width, height: self.frame.size.height ))
contactNode.physicsBody?.isDynamic = false
contactNode.physicsBody?.categoryBitMask = scoreCategory
contactNode.physicsBody?.contactTestBitMask = birdCategory
pipePair.addChild(contactNode)
pipePair.run(movePipesAndRemove)
pipes.addChild(pipePair)
}
func resetScene () {
// Move bird to original position and reset velocity
bird.position = CGPoint(x: self.frame.size.width / 2.5, y: self.frame.midY)
bird.physicsBody?.velocity = CGVector( dx: 0, dy: 0 )
bird.physicsBody?.collisionBitMask = worldCategory | pipeCategory
bird.speed = 1.0
bird.zRotation = 0.0
// Remove all existing pipes
pipes.removeAllChildren()
// Reset _canRestart
canRestart = false
// Reset score
score = 0
scoreLabelNode.text = String(score)
// Restart animation
moving.speed = 1
// GENETIC ALGORITHM (DOWN BELOW)
// Calculate the amount of time it took until the AI lost.
let endDate: NSDate = NSDate()
let timeInterval: Double = endDate.timeIntervalSince(currentTimeForFlappyBird as Date)
currentTimeForFlappyBird = NSDate()
// Evaluate the current birds fitness
if let bird = currentBird {
bird.generateFitness(score: score, time: Float(timeInterval))
// Current generation, bird, and fitness of current bird information
print("--------------------------- \n")
print("GENERATION: \(generationCounter)")
print("BIRD COUNT: \(currentFlappy)")
print("FITNESS: \(bird.fitness)")
self.generationLabel.text = "Gen: \(self.generationCounter)"
print("--------------------------- \n")
if bird.fitness >= 9.0 {
print("FOUND RARE BIRD")
print(bird.brain?.layers[0].weights)
print(bird.brain?.layers[1].weights)
print(bird.brain?.layers[0].bias)
print(bird.brain?.layers[1].bias)
}
}
// Go to next flappy bird
currentFlappy += 1
if let generation = flappyBirdGenerationContainer {
// Experiment: Keep some of the last best birds and put them back into the population
lastBestGen = generation.filter({$0.fitness >= 6.0})
if lastBestGen.count > 10 {
// We want to make room for unique birds
lastBestGen = Array<FlappyGenome>(lastBestGen[0...6])
}
}
if let bird = currentBird {
if bird.fitness > maxFitness {
maxFitness = bird.fitness
maxBird = bird
}
}
// If we have hit the 20th bird, we need to move on to the next generation
if currentFlappy == 20 {
print("GENERATING NEW GEN!")
currentFlappy = 0
// New generation array
var newGen: [FlappyGenome] = []
newGen = lastBestGen
if let bestBird = maxBird {
flappyBirdGenerationContainer?.append(bestBird)
}
while newGen.count < 20 {
// Select the best parents
let parents = PopulationManager.selectParents(genomes: flappyBirdGenerationContainer!)
print("PARENT 1 FITNESS: \(parents.0.fitness)")
print("PARENT 2 FITNESS: \(parents.1.fitness)")
// Produce new flappy birds
var offspring = BiologicalProcessManager.onePointCrossover(crossoverRate: 0.5, parentOneGenotype: parents.0.genotypeRepresentation, parentTwoGenotype: parents.1.genotypeRepresentation)
// Mutate their genes
BiologicalProcessManager.inverseMutation(mutationRate: 0.7, genotype: &offspring.0)
BiologicalProcessManager.inverseMutation(mutationRate: 0.7, genotype: &offspring.1)
// Create a separate neural network for the birds based on their genes
let brainofOffspring1 = GeneticOperations.decode(genotype: offspring.0)
let brainofOffspring2 = GeneticOperations.decode(genotype: offspring.1)
let offspring1 = FlappyGenome(genotype: offspring.0, network: brainofOffspring1)
let offspring2 = FlappyGenome(genotype: offspring.1, network: brainofOffspring2)
// Add them to the new generation
newGen.append(offspring1)
newGen.append(offspring2)
}
generationCounter += 1
// Replace the old generation
flappyBirdGenerationContainer = newGen
// Set the current bird
if let generation = flappyBirdGenerationContainer {
if generation.count > currentFlappy {
currentBird = generation[currentFlappy]
} else {
if let bestBird = maxBird {
currentBird = maxBird
}
}
}
} else {
// Set the current bird
if let generation = flappyBirdGenerationContainer {
if generation.count > currentFlappy {
currentBird = generation[currentFlappy]
}
} else {
currentBird = maxBird
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if moving.speed > 0 {
for _ in touches { // do we need all touches?
}
} else if canRestart {
self.resetScene()
}
}
// Chooses the closest pipe
func closestPipe(pipes: [SKNode]) -> Int {
var min = 0
var minDist = abs(pipes[0].position.x - bird.position.x)
for (i, pipe) in pipes.enumerated() {
if abs(pipe.position.x - minDist) < minDist {
minDist = abs(pipe.position.x - minDist)
min = i
}
}
return min
}
override func update(_ currentTime: TimeInterval) {
let endDate: NSDate = NSDate()
let timeInterval: Double = endDate.timeIntervalSince(currentTimeForFlappyBird as Date)
self.fitnessLabel.text = "Fitness: \(NSString(format: "%.2f", timeInterval))"
checkIfOutOfBounds(bird.position.y)
/* Called before each frame is rendered */
let value = bird.physicsBody!.velocity.dy * ( bird.physicsBody!.velocity.dy < 0 ? 0.003 : 0.001 )
bird.zRotation = min( max(-1, value), 0.5 )
// If the pipes are now visible...
if pipes.children.count > 0 {
// Check to see if the pipe in front has gone behind the bird
// if so, make the new pipe in front of the bird the target pipe
if pipes.children.count > 1 {
if pipes.children[currentPipe].position.x < bird.position.x {
currentPipe = closestPipe(pipes: pipes.children)
}
}
if pipes.children.count == 1 {
if pipes.children[0].position.x < bird.position.x {
currentPipe = 0
}
}
// Distance between next pipe and bird
let distanceOfNextPipe = abs(pipes.children[currentPipe].position.x - bird.position.x)
let distanceFromBottomPipe = abs(pipes.children[currentPipe].children[1].position.y - bird.position.y)
let normalizedDistanceFromBottomPipe = (distanceFromBottomPipe - 5)/(708 - 5)
let normalizedDistanceOfNextPipe = (distanceOfNextPipe - 3)/(725-3)
let distanceFromTheGround = abs(self.bird.position.y - self.moving.children[1].position.y)
let normalizedDistanceFromTheGround = (distanceFromTheGround - 135)/(840-135)
let distanceFromTheSky = abs(880 - self.bird.position.y)
let normalizedDistanceFromTheSky = distanceFromTheSky/632
// Bird Y position
let birdYPos = bird.position.y/CGFloat(880)
// Measure how close the bird is to the gap between the pipes
let posToGap = pipes.children[0].children[2].position.y - bird.position.y
let normalizedPosToGap = (posToGap - (-439))/(279 - (-439))
if let flappyBird = currentBird {
// Decision AI makes
let input = Matrix<Float>(rows: 6, columns: 1, elements: [Float(normalizedDistanceOfNextPipe), Float(normalizedPosToGap), Float(birdYPos), Float(normalizedDistanceFromBottomPipe), Float(normalizedDistanceFromTheGround), Float(normalizedDistanceFromTheSky)])
let potentialDescision = flappyBird.brain?.feedforward(input: input)
if let decision = potentialDescision {
print("FLAPPY BIRD DECISION: \(decision)")
if (decision.elements[0]) >= Float(0.5) {
if moving.speed > 0 {
bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 30))
}
}
}
}
}
if canRestart {
// If the game ends...
// record the current flappy birds fitness...
// then bring in the next flappy bird
self.resetScene()
}
}
// Checks if the bird is at the top of the screen
func checkIfOutOfBounds(_ y: CGFloat) {
if moving.speed > 0 {
if y >= 880 {
moving.speed = 0
bird.physicsBody?.collisionBitMask = worldCategory
bird.run( SKAction.rotate(byAngle: CGFloat(M_PI) * CGFloat(bird.position.y) * 0.01, duration:1), completion: {self.bird.speed = 0 })
// Flash background if contact is detected
self.removeAction(forKey: "flash")
self.run(SKAction.sequence([SKAction.repeat(SKAction.sequence([SKAction.run({
//self.backgroundColor = SKColor(red: 1, green: 0, blue: 0, alpha: 1.0)
}), SKAction.wait(forDuration: TimeInterval(0.05)), SKAction.run({
self.backgroundColor = self.skyColor
}), SKAction.wait(forDuration: TimeInterval(0.05))]), count:4), SKAction.run({
self.canRestart = true
})]), withKey: "flash")
}
}
}
func didBegin(_ contact: SKPhysicsContact) {
if moving.speed > 0 {
if ( contact.bodyA.categoryBitMask & scoreCategory ) == scoreCategory || ( contact.bodyB.categoryBitMask & scoreCategory ) == scoreCategory {
// Bird has contact with score entity
score += 1
scoreLabelNode.text = String(score)
// Update best score label
if score > bestScore {
bestScore = score
bestScoreLabel.text = "Best Score: \(self.bestScore)"
}
// Add a little visual feedback for the score increment
scoreLabelNode.run(SKAction.sequence([SKAction.scale(to: 1.5, duration:TimeInterval(0.1)), SKAction.scale(to: 1.0, duration:TimeInterval(0.1))]))
} else {
moving.speed = 0
bird.physicsBody?.collisionBitMask = worldCategory
bird.run( SKAction.rotate(byAngle: CGFloat(M_PI) * CGFloat(bird.position.y) * 0.01, duration:1), completion: {self.bird.speed = 0 })
// Flash background if contact is detected
self.removeAction(forKey: "flash")
self.run(SKAction.sequence([SKAction.repeat(SKAction.sequence([SKAction.run({
//self.backgroundColor = SKColor(red: 1, green: 0, blue: 0, alpha: 1.0)
}), SKAction.wait(forDuration: TimeInterval(0.05)), SKAction.run({
self.backgroundColor = self.skyColor
}), SKAction.wait(forDuration: TimeInterval(0.05))]), count:4), SKAction.run({
self.canRestart = true
})]), withKey: "flash")
}
}
}
}
|
08d1875734e439d9aafb81295e9fc823
| 35.961921 | 273 | 0.606226 | false | false | false | false |
jeremiahyan/ResearchKit
|
refs/heads/main
|
ResearchKit/ActiveTasks/ORKSwiftStroopStep.swift
|
bsd-3-clause
|
3
|
/*
Copyright (c) 2019, 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 Foundation
public class ORKSwiftStroopStep: ORKActiveStep {
public var numberOfAttempts = 0
private let minimumAttempts = 10
enum Key: String {
case numberOfAttempts
}
public override class func stepViewControllerClass() -> AnyClass {
return ORKSwiftStroopStepViewController.self
}
public class func supportsSecureCoding() -> Bool {
return true
}
public override init(identifier: String) {
super.init(identifier: identifier)
shouldVibrateOnStart = true
shouldShowDefaultTimer = false
shouldContinueOnFinish = true
stepDuration = TimeInterval(NSIntegerMax)
}
public override func validateParameters() {
super.validateParameters()
assert(numberOfAttempts >= minimumAttempts, "number of attempts should be greater or equal to \(minimumAttempts)")
}
public override func startsFinished() -> Bool {
return false
}
public override var allowsBackNavigation: Bool {
return false
}
public override func copy(with zone: NSZone? = nil) -> Any {
let stroopStep = super.copy(with: zone)
return stroopStep
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
numberOfAttempts = aDecoder.decodeInteger(forKey: Key.numberOfAttempts.rawValue)
}
public override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(numberOfAttempts, forKey: Key.numberOfAttempts.rawValue)
}
public override func isEqual(_ object: Any?) -> Bool {
if let object = object as? ORKSwiftStroopStep {
return numberOfAttempts == object.numberOfAttempts
}
return false
}
}
|
c6b95e7a3799c42683ba8c278f957fbb
| 35.691489 | 122 | 0.719919 | false | false | false | false |
BasThomas/Analysis
|
refs/heads/main
|
Example/Analysis/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Analysis
//
// Created by Bas Broek on 11/11/2016.
// Copyright (c) 2016 Bas Broek. All rights reserved.
//
import UIKit
private let analyseIdentifier = "analyse"
class ViewController: UIViewController {
@IBOutlet var analyseBarButtonItem: UIBarButtonItem!
@IBOutlet var textView: UITextView! {
didSet {
textView.becomeFirstResponder()
analyseBarButtonItem.isEnabled = !textView.text.isEmpty
}
}
}
// MARK: - Text view delegate
extension ViewController: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
analyseBarButtonItem.isEnabled = !textView.text.isEmpty
}
}
// MARK: - Actions
extension ViewController {
@IBAction func analyse(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: analyseIdentifier, sender: self)
}
}
// MARK: - Navigation
extension ViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destinationViewController = segue.destination as? AnalysisTableViewController else { return }
destinationViewController.input = textView.text
}
}
|
17491a587087b9dcc97325f9b2e09634
| 22.978723 | 107 | 0.732032 | false | false | false | false |
arloistale/iOSThrive
|
refs/heads/master
|
Thrive/Thrive/MoodControl.swift
|
mit
|
1
|
//
// MoodControl.swift
// Thrive
//
// Created by Jonathan Lu on 2/7/16.
// Copyright © 2016 UCSC OpenLab. All rights reserved.
//
import UIKit
class MoodControl: UIView {
// MARK: Properties
private var selectedMood = 0 {
didSet {
setNeedsLayout()
}
}
private var moodButtons = [UIButton]()
private var buttonSpacing = 5
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
for (index, mood) in JournalEntry.MoodType.values.enumerate() {
let normalImage = UIImage(named: mood.rawValue)
let tintedImage = normalImage?.imageWithRenderingMode(.AlwaysTemplate)
let button = UIButton()
button.setImage(tintedImage, forState: .Normal)
button.setImage(tintedImage, forState: .Selected)
button.setImage(tintedImage, forState: [.Highlighted, .Selected])
button.tintColor = JournalEntry.MoodType.colors[index]
button.addTarget(self, action: "moodButtonPressed:", forControlEvents: .TouchDown)
moodButtons += [button]
addSubview(button)
}
}
override func layoutSubviews() {
// adjust buttons to size of container
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
for (index, button) in moodButtons.enumerate() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + buttonSpacing))
button.frame = buttonFrame
}
moodButtons[selectedMood].selected = true
}
override func intrinsicContentSize() -> CGSize {
let buttonSize = Int(frame.size.height)
let width = (buttonSize + 5) * JournalEntry.MoodType.values.count
return CGSize(width: width, height: buttonSize)
}
// MARK: Button Actions
func moodButtonPressed(button: UIButton) {
// unselect previously selected button
moodButtons[selectedMood].selected = false
// select new button
selectedMood = moodButtons.indexOf(button)!
button.selected = true;
}
// MARK: Getters
func getSelectedMoodIndex() -> Int {
return selectedMood
}
}
|
9485f006e4d8fc80402d3a581fb25bdf
| 28.219512 | 94 | 0.599332 | false | false | false | false |
sgr-ksmt/SUNetworkActivityIndicator
|
refs/heads/master
|
SUNetworkActivityIndicator/SUNetworkActivityIndicator.swift
|
mit
|
1
|
//
// SUNetworkActivityIndicator.swift
//
// Created by Suguru Kishimoto on 2015/12/17.
import Foundation
import UIKit
/**
Notification name for `activeCount` changed.
Contains `activeCount` in notification.object as `Int`
*/
public let NetworkActivityIndicatorActiveCountChangedNotification = "ActiveCountChanged"
/// NetworkActivityIndicator
public class NetworkActivityIndicator {
/// Singleton: shared instance (private var)
private static let sharedInstance = NetworkActivityIndicator()
/// enable sync access (like Objective-C's `@synchronized`)
private let syncQueue = dispatch_queue_create(
"NetworkActivityIndicatorManager.syncQueue",
DISPATCH_QUEUE_SERIAL
)
/**
ActiveCount
If count is above 0,
```
UIApplication.sharedApplication().networkActivityIndicatorVisible
```
is true, else false.
*/
private(set) public var activeCount: Int {
didSet {
UIApplication.sharedApplication()
.networkActivityIndicatorVisible = activeCount > 0
if activeCount < 0 {
activeCount = 0
}
NSNotificationCenter.defaultCenter().postNotificationName(
NetworkActivityIndicatorActiveCountChangedNotification,
object: activeCount
)
}
}
/**
Initializer (private)
- returns: instance
*/
private init() {
self.activeCount = 0
}
public class func shared() -> NetworkActivityIndicator {
return sharedInstance
}
/**
Count up `activeCount` and `networkActivityIndicatorVisible` change to true.
*/
public func start() {
dispatch_sync(syncQueue) { [unowned self] in
self.activeCount += 1
}
}
/**
Count down `activeCount` and if count is zero, `networkActivityIndicatorVisible` change to false.
*/
public func end() {
dispatch_sync(syncQueue) { [unowned self] in
self.activeCount -= 1
}
}
/**
Reset `activeCount` and `networkActivityIndicatorVisible` change to false.
*/
public func endAll() {
dispatch_sync(syncQueue) { [unowned self] in
self.activeCount = 0
}
}
}
|
7f2746ea3adb46e78029b607805fa15b
| 21.655914 | 100 | 0.67869 | false | false | false | false |
wangyaqing/LeetCode-swift
|
refs/heads/master
|
Solutions/4. Median of Two Sorted Arrays.playground/Contents.swift
|
mit
|
1
|
import UIKit
import Foundation
class Solution {
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
var a = nums1, b = nums2, m = a.count, n = b.count
if m > n {
return findMedianSortedArrays(nums2, nums1)
}
var min = 0, max = m
while min <= max {
let i = (min + max) / 2
let j = (m + n + 1) / 2 - i
if j != 0, i != m, b[j-1] > a[i] {
min = i + 1
} else if i != 0, j != n, a[i-1] > b[j] {
max = i - 1
} else {
var left = 0
if i == 0 {
left = b[j-1]
} else if j == 0 {
left = a[i-1]
} else {
left = a[i-1] > b[j-1] ? a[i-1] : b[j-1]
}
if (m + n) % 2 == 1 {
return Double(left)
}
var right = 0
if i == m {
right = b[j]
} else if j == n {
right = a[i]
} else {
right = a[i] < b[j] ? a[i] : b[j]
}
return Double(left + right)/2
}
}
return 0
}
}
Solution().findMedianSortedArrays([1,3], [2])
|
ac22759f3c1ce200a935d70968141370
| 27.583333 | 75 | 0.31414 | false | false | false | false |
tnako/Challenge_ios
|
refs/heads/master
|
Challenge/ChallengesController.swift
|
gpl-3.0
|
1
|
//
// FirstViewController.swift
// Challenge
//
// Created by Anton Korshikov on 25.09.15.
// Copyright © 2015 Anton Korshikov. All rights reserved.
//
import UIKit
import SwiftEventBus
import SwiftyJSON
// ToDo: разобраться с датой, учитывая часовой пояс
struct Challenge {
var num: Int?;
var action: String?;
var start: timeb?;
var end: timeb?;
var item: String?;
var place: String?;
var person: String?;
init(num: Int?, action: String?,
start: timeb?, end: timeb?,
item: String?, place: String?, person: String?) {
self.num = num;
self.action = action;
self.start = start;
self.end = end;
self.item = item;
self.place = place;
self.person = person;
}
}
class ChallengesController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var ChallengesTable: UITableView!;
var ChallengesArray = [Challenge]()
//var SelectedRow:Int?;
override func viewDidLoad() {
super.viewDidLoad()
SwiftEventBus.post("getChallenges")
SwiftEventBus.onMainThread(self, name: "challenges_list") { result in
let list = (result?.object as! NSArray) as Array;
self.ChallengesArray.removeAll()
for (var i = 0; i < list.count; ++i) {
print("one line : \(list[i])")
let json = JSON(list[i])
var endDate:timeb = timeb();
endDate.time = time_t(arc4random_uniform(98) + 1);
self.ChallengesArray.append(Challenge(num: json["challenge_id"].intValue, action: json["action_id"].stringValue, start: timeb(), end: endDate, item: json["item_id"].stringValue, place: json["where_id"].stringValue, person: json["who_id"].stringValue));
}
self.ChallengesTable.reloadData()
}
ChallengesTable.delegate = self
ChallengesTable.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ChallengesArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = ChallengesTable.dequeueReusableCellWithIdentifier("OneRow", forIndexPath: indexPath) as! ChallengesTableViewCell
let row = indexPath.row
cell.HeaderLabel?.text = "Quest #\(ChallengesArray[row].num!)";
let minutes:UInt = UInt(ChallengesArray[row].end!.time);
if (minutes > 90 || minutes < 10) {
// проголосовал сам или учавствовал
cell.accessoryType = .Checkmark;
} else {
cell.accessoryType = .DisclosureIndicator;
}
if (minutes > 70) {
cell.backgroundColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1);
cell.TimerLabel.text = "Start in \(minutes) minute";
cell.ProgressBar.progress = Float(minutes) / 100.0;
} else {
cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1);
cell.TimerLabel.text = "Ends in \(minutes) minute";
cell.ProgressBar.progress = 1 - Float(minutes) / 100.0;
}
return cell
}
/*
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
ChallengesTable.deselectRowAtIndexPath(indexPath, animated: true)
SelectedRow = indexPath.row;
}
override func prefersStatusBarHidden() -> Bool {
if self.navigationController?.navigationBarHidden == true {
return true
} else {
return false
}
}
*/
// ToDo: передача выбранного номера
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowChallenge" {
print("ShowChallenge debug");
if let indexPath = self.ChallengesTable.indexPathForSelectedRow {
let challenge = ChallengesArray[indexPath.row];
let controller = segue.destinationViewController as! ChallengeDetailViewController;
//controller.PhotoArray.append("Quest #\(challenge.num!)");
//ToDo: передача номера квеста
}
}
}
}
|
a1d59f1c8bd26bb777495122d29b0bc9
| 31.282759 | 268 | 0.596881 | false | false | false | false |
artsy/eigen
|
refs/heads/main
|
ios/Artsy/View_Controllers/Live_Auctions/LotListCollectionViewCell.swift
|
mit
|
1
|
import UIKit
import Interstellar
class LotListCollectionViewCell: UICollectionViewCell {
static let CellIdentifier = "LotCellIdentifier"
static let Height: CGFloat = 80
let lotImageView = UIImageView()
let hammerImageView = UIImageView(image: UIImage(asset: .Lot_bidder_hammer_white))
let labelContainerView = LotListCollectionViewCell._labelContainerView()
let closedLabel = LotListCollectionViewCell._closedLabel()
let currentLotIndicatorImageView = UIImageView()
let lotNumberLabel = LotListCollectionViewCell._lotNumberLabel()
let artistsNamesLabel = LotListCollectionViewCell._artistNamesLabel()
let currentAskingPriceLabel = LotListCollectionViewCell._currentAskingPriceLabel()
let topSeparator = ARSeparatorView()
let bottomSeparator = ARSeparatorView()
var isNotTopCell = true
fileprivate var userInterfaceNeedsSetup = true
fileprivate var lotStateSubscription: ObserverToken<LotState>?
fileprivate var askingPriceSubscription: ObserverToken<UInt64>?
deinit {
lotStateSubscription?.unsubscribe()
askingPriceSubscription?.unsubscribe()
}
}
private typealias Overrides = LotListCollectionViewCell
extension Overrides {
override func prepareForReuse() {
super.prepareForReuse()
defer {
lotStateSubscription = nil
askingPriceSubscription = nil
}
lotStateSubscription?.unsubscribe()
askingPriceSubscription?.unsubscribe()
}
}
private typealias PublicFunctions = LotListCollectionViewCell
extension PublicFunctions {
func configureForViewModel(_ viewModel: LiveAuctionLotViewModelType, indexPath: IndexPath) {
let currencySymbol = viewModel.currencySymbol
if userInterfaceNeedsSetup {
userInterfaceNeedsSetup = false
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.align(toView: self)
lotImageView.contentMode = .scaleAspectFill
lotImageView.clipsToBounds = true
}
resetViewHierarchy()
isNotTopCell = (indexPath.item > 0)
self.lotStateSubscription = viewModel.lotStateSignal.subscribe { [weak self] state in
self?.setLotState(state)
}
askingPriceSubscription = viewModel
.askingPriceSignal
.subscribe { [weak self] askingPrice in
self?.currentAskingPriceLabel.text = askingPrice.convertToDollarString(currencySymbol)
return
}
lotImageView.ar_setImage(with: viewModel.urlForThumbnail)
lotNumberLabel.text = viewModel.formattedLotIndexDisplayString
artistsNamesLabel.text = viewModel.lotArtist
}
}
|
daff6bf6e7bfcd34c464919c0784c1e6
| 34.166667 | 102 | 0.716734 | false | false | false | false |
azukinohiroki/positionmaker2
|
refs/heads/master
|
positionmaker2/CoreDataHelper.swift
|
mit
|
1
|
//
// CoreDataHelper.swift
// positionmaker2
//
// Created by Hiroki Taoka on 2015/06/11.
// Copyright (c) 2015年 azukinohiroki. All rights reserved.
//
import Foundation
import CoreData
class CoreDataHelper {
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.azk.hr.positionmaker2" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "positionmaker2", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("positionmaker2.sqlite")
var error: NSError? = nil
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 var error1 as NSError {
error = error1
coordinator = nil
// 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
error = 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 \(String(describing: error)), \(error!.userInfo)")
// abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(String(describing: error)), \(error!.userInfo)")
// abort()
}
}
}
}
}
|
ef59019ee2acf516804f73beb3e36072
| 46.069767 | 286 | 0.720356 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Rules/Style/UnusedOptionalBindingRule.swift
|
mit
|
1
|
import SwiftSyntax
struct UnusedOptionalBindingRule: SwiftSyntaxRule, ConfigurationProviderRule {
var configuration = UnusedOptionalBindingConfiguration(ignoreOptionalTry: false)
init() {}
static let description = RuleDescription(
identifier: "unused_optional_binding",
name: "Unused Optional Binding",
description: "Prefer `!= nil` over `let _ =`",
kind: .style,
nonTriggeringExamples: [
Example("if let bar = Foo.optionalValue {\n" +
"}\n"),
Example("if let (_, second) = getOptionalTuple() {\n" +
"}\n"),
Example("if let (_, asd, _) = getOptionalTuple(), let bar = Foo.optionalValue {\n" +
"}\n"),
Example("if foo() { let _ = bar() }\n"),
Example("if foo() { _ = bar() }\n"),
Example("if case .some(_) = self {}"),
Example("if let point = state.find({ _ in true }) {}")
],
triggeringExamples: [
Example("if let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {\n" +
"}\n"),
Example("guard let a = Foo.optionalValue, let ↓_ = Foo.optionalValue2 {\n" +
"}\n"),
Example("if let (first, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let (first, _) = getOptionalTuple(), let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let (_, second) = getOptionalTuple(), let ↓_ = Foo.optionalValue {\n" +
"}\n"),
Example("if let ↓(_, _, _) = getOptionalTuple(), let bar = Foo.optionalValue {\n" +
"}\n"),
Example("func foo() {\nif let ↓_ = bar {\n}\n")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(ignoreOptionalTry: configuration.ignoreOptionalTry)
}
}
private extension UnusedOptionalBindingRule {
final class Visitor: ViolationsSyntaxVisitor {
private let ignoreOptionalTry: Bool
init(ignoreOptionalTry: Bool) {
self.ignoreOptionalTry = ignoreOptionalTry
super.init(viewMode: .sourceAccurate)
}
override func visitPost(_ node: OptionalBindingConditionSyntax) {
guard let pattern = node.pattern.as(ExpressionPatternSyntax.self),
pattern.expression.isDiscardExpression else {
return
}
if ignoreOptionalTry,
let tryExpr = node.initializer?.value.as(TryExprSyntax.self),
tryExpr.questionOrExclamationMark?.tokenKind == .postfixQuestionMark {
return
}
violations.append(pattern.expression.positionAfterSkippingLeadingTrivia)
}
}
}
private extension ExprSyntax {
var isDiscardExpression: Bool {
if self.is(DiscardAssignmentExprSyntax.self) {
return true
} else if let tuple = self.as(TupleExprSyntax.self) {
return tuple.elementList.allSatisfy { elem in
elem.expression.isDiscardExpression
}
}
return false
}
}
|
2330d1a66559c3bd80340071d306d30c
| 36.218391 | 99 | 0.561149 | false | false | false | false |
wwq0327/iOS9Example
|
refs/heads/master
|
DemoLists/DemoLists/HomePageAnimationUtil.swift
|
apache-2.0
|
1
|
//
// HomePageAnimationUtil.swift
// DemoLists
//
// Created by wyatt on 15/12/3.
// Copyright © 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
let kBottomLineWith: CGFloat = 272.0
class HomePageAnimationUtil: NSObject {
// 顶端两行label的动画
class func titleLabelAnimationWithLabel(label: UILabel, view: UIView) {
UIView.animateWithDuration(1) { () -> Void in
label.transform = CGAffineTransformIdentity
}
}
// 手机图标的动画
class func phoneIconImageViewAnimation(imageView: UIImageView, view: UIView) {
UIView.animateWithDuration(1.5, animations: { () -> Void in
// 回归原始位置
imageView.transform = CGAffineTransformIdentity
// 透明度为1,即完全显示出imageview
imageView.alpha = 1.0
}, completion: nil)
}
// 直线的动画
class func textFieldBottomLineAnimationWithConstraint(constraint: NSLayoutConstraint, view: UIView) {
// 先设定好约束,但此是在界面上并没有进行刷新
constraint.constant = kBottomLineWith
UIView.animateWithDuration(1.5) { () -> Void in
// 开始界面刷新,线束开始起作用
view.layoutIfNeeded()
}
}
// 按钮动画
class func registerButtonAnimation(button: UIButton, view: UIView, progress: CGFloat) {
}
// 版权文字动画
class func tipsLabelMaskAnination(view: UIView, beginTime: NSTimeInterval) {
}
}
|
644cbaf3a05d5d5003f3dddc78e3d914
| 25.811321 | 105 | 0.622097 | false | false | false | false |
lawrencelomax/XMLParsable
|
refs/heads/master
|
XMLParsable/XML/LibXML/LibXMLDOM.swift
|
mit
|
1
|
//
// LibXMLDOM.swift
// XMLParsable
//
// Created by Lawrence Lomax on 26/08/2014.
// Copyright (c) 2014 Lawrence Lomax. All rights reserved.
//
import Foundation
import swiftz_core
public let LibXMLDOMErrorDomain = InMyDomain("libxml.dom")
typealias LibXMLDOMNodeSequence = SequenceOf<xmlNodePtr>
internal final class LibXMLDOM {
struct Context {
let document: xmlDocPtr
let rootNode: xmlNodePtr
init (document: xmlDocPtr, rootNode: xmlNodePtr){
self.document = document
self.rootNode = rootNode
}
func dispose() {
if self.rootNode != nil {
xmlFreeDoc(self.document)
}
}
}
internal class func error(message: String) -> NSError {
return NSError(domain: LibXMLDOMErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: message])
}
internal class func createWithURL(url: NSURL) -> Result<LibXMLDOM.Context> {
let document = self.documentPointer(url)
return { LibXMLDOM.Context(document: document, rootNode: $0) } <^> self.rootNode(document)
}
internal class func createWithData(data: NSData) -> Result<LibXMLDOM.Context> {
let document = self.documentPointer(data)
return { LibXMLDOM.Context(document: document, rootNode: $0) } <^> self.rootNode(document)
}
internal class func childrenOfNode(node: xmlNodePtr) -> LibXMLDOMNodeSequence {
var nextNode = LibXMLDOMGetChildren(node)
let generator: GeneratorOf<xmlNodePtr> = GeneratorOf {
if (nextNode == nil) {
return nil
}
let currentNode = nextNode
nextNode = LibXMLDOMGetSibling(nextNode)
return currentNode
}
return SequenceOf(generator)
}
private class func rootNode(document: xmlDocPtr) -> Result<xmlNodePtr> {
if document == nil {
return Result.error(self.error("Could Not Parse Document"))
}
let rootNode = xmlDocGetRootElement(document)
if rootNode == nil {
xmlFreeDoc(document)
return Result.error(self.error("Could Not Get Root element"))
}
return Result.value(rootNode)
}
private class func documentPointer(url: NSURL) -> xmlDocPtr {
let urlString = url.path
let cString = urlString?.cStringUsingEncoding(NSUTF8StringEncoding)
return xmlParseFile(cString!)
}
private class func documentPointer(data: NSData) -> xmlDocPtr {
let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
let cString = string.UTF8String
let length = strlen(cString)
return xmlParseMemory(cString, Int32(length))
}
}
|
78434883d8d52337ec91d0a8f1ad6175
| 28.113636 | 105 | 0.685792 | false | false | false | false |
tablexi/txi-ios-bootstrap
|
refs/heads/develop
|
Example/Tests/Managers/EnvironmentManagerSpec.swift
|
mit
|
1
|
//
// EnvironmentManagerSpec.swift
// TXIBootstrap
//
// Created by Ed Lafoy on 12/11/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import TXIBootstrap
class EnvironmentManagerSpec: QuickSpec {
var bundle: Bundle { return Bundle(for: type(of: self)) }
let userDefaults = UserDefaults(suiteName: "test")!
let userDefaultsKey = "environment"
var environmentValues: [[String: AnyObject]] {
let path = self.bundle.path(forResource: "Environments", ofType: "plist")!
let values = NSArray(contentsOfFile: path) as? [[String: AnyObject]]
return values ?? []
}
var environmentManager: EnvironmentManager<TestEnvironment>!
override func spec() {
beforeEach {
self.userDefaults.setValue("", forKey: self.userDefaultsKey)
expect(self.environmentValues.count).to(beGreaterThan(0))
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
}
it("reads environments from Environments.plist") {
expect(self.environmentManager.environments.count).to(equal(self.environmentValues.count))
}
it("populates valid environments") {
self.validateEnvironmentAtIndex(index: 0)
self.validateEnvironmentAtIndex(index: 1)
}
it("saves the selected environment in user defaults") {
let environment1 = self.environmentManager.environments[0]
let environment2 = self.environmentManager.environments[1]
self.environmentManager.currentEnvironment = environment1
expect(self.userDefaults.value(forKey: self.userDefaultsKey) as? String).to(equal(environment1.name))
self.environmentManager.currentEnvironment = environment2
expect(self.userDefaults.value(forKey: self.userDefaultsKey) as? String).to(equal(environment2.name))
}
it("shows the correct current environment if it's changed elsewhere by another instance of EnvironmentManager") {
let otherEnvironmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.currentEnvironment))
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.environments[0]))
self.environmentManager.currentEnvironment = self.environmentManager.environments[1]
expect(otherEnvironmentManager.currentEnvironment).to(equal(self.environmentManager.currentEnvironment))
}
context("with no stored environment") {
var defaultEnvironment: TestEnvironment!
beforeEach {
self.userDefaults.setValue("", forKey: self.userDefaultsKey)
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
defaultEnvironment = self.environmentManager.environments[0]
}
it("defaults to first environment") {
expect(self.environmentManager.currentEnvironment).to(equal(defaultEnvironment))
}
}
context("with saved environment") {
beforeEach {
self.userDefaults.setValue("Stage", forKey: self.userDefaultsKey)
self.environmentManager = EnvironmentManager<TestEnvironment>(userDefaults: self.userDefaults, bundle: self.bundle)
}
it("uses the saved environment") {
guard let stageEnvironment = self.environmentManager.environments.filter({ $0.name == "Stage" }).first else { return fail() }
expect(self.environmentManager.currentEnvironment).to(equal(stageEnvironment))
}
}
}
func validateEnvironmentAtIndex(index: Int) {
let environment = environmentManager.environments[index]
let values = environmentValues[index]
guard let name = values["Name"] as? String,
let domain = values["Domain"] as? String,
let key = values["Key"] as? String else { return fail() }
expect(environment.name).to(equal(name))
expect(environment.domain).to(equal(domain))
expect(environment.key).to(equal(key))
}
}
class TestEnvironment: Environment, CustomDebugStringConvertible {
var name: String = ""
var domain: String = ""
var key: String = ""
required init?(environment: [String: AnyObject]) {
guard let name = environment["Name"] as? String, let domain = environment["Domain"] as? String, let key = environment["Key"] as? String else { return nil }
self.name = name
self.domain = domain
self.key = key
}
var debugDescription: String { return self.name }
}
func ==(left: TestEnvironment, right: TestEnvironment) -> Bool { return left.name == right.name }
|
cb3f4ffc2e1827fd29017eb6b6457e62
| 38.754237 | 159 | 0.715199 | false | true | false | false |
jemartti/Hymnal
|
refs/heads/master
|
Hymnal/ScheduleViewController.swift
|
mit
|
1
|
//
// ScheduleViewController.swift
// Hymnal
//
// Created by Jacob Marttinen on 5/6/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import UIKit
import CoreData
// MARK: - ScheduleViewController: UITableViewController
class ScheduleViewController: UITableViewController {
// MARK: Properties
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var indicator: UIActivityIndicatorView!
var schedule: [ScheduleLineEntity]!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initialiseUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Check if it's time to update the schedule
var forceFetch = false
if !UserDefaults.standard.bool(forKey: "hasFetchedSchedule") {
forceFetch = true
} else {
let lastScheduleFetch = UserDefaults.standard.double(forKey: "lastScheduleFetch")
if (lastScheduleFetch + 60*60*24 < NSDate().timeIntervalSince1970) {
forceFetch = true
}
}
// Check for existing Schedule in Model
let scheduleFR = NSFetchRequest<NSManagedObject>(entityName: "ScheduleLineEntity")
scheduleFR.sortDescriptors = [NSSortDescriptor(key: "sortKey", ascending: true)]
do {
let scheduleLineEntities = try appDelegate.stack.context.fetch(scheduleFR) as! [ScheduleLineEntity]
if scheduleLineEntities.count <= 0 || forceFetch {
schedule = [ScheduleLineEntity]()
fetchSchedule()
} else {
schedule = scheduleLineEntities
tableView.reloadData()
}
} catch _ as NSError {
alertUserOfFailure(message: "Data load failed.")
}
}
// UI+UX Functionality
private func initialiseUI() {
view.backgroundColor = .white
indicator = createIndicator()
// Set up the Navigation bar
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.stop,
target: self,
action: #selector(ScheduleViewController.returnToRoot)
)
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.refresh,
target: self,
action: #selector(ScheduleViewController.fetchSchedule)
)
navigationItem.title = "Schedule"
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = Constants.UI.Armadillo
navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: Constants.UI.Armadillo
]
}
private func createIndicator() -> UIActivityIndicatorView {
let indicator = UIActivityIndicatorView(
style: UIActivityIndicatorView.Style.gray
)
indicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0);
indicator.center = view.center
view.addSubview(indicator)
indicator.bringSubviewToFront(view)
return indicator
}
private func alertUserOfFailure( message: String) {
DispatchQueue.main.async {
let alertController = UIAlertController(
title: "Action Failed",
message: message,
preferredStyle: UIAlertController.Style.alert
)
alertController.addAction(UIAlertAction(
title: "Dismiss",
style: UIAlertAction.Style.default,
handler: nil
))
self.present(alertController, animated: true, completion: nil)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
@objc func returnToRoot() {
dismiss(animated: true, completion: nil)
}
// MARK: Data Management Functions
@objc func fetchSchedule() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
indicator.startAnimating()
MarttinenClient.sharedInstance().getSchedule() { (scheduleRaw, error) in
if error != nil {
self.alertUserOfFailure(message: "Data download failed.")
} else {
self.appDelegate.stack.performBackgroundBatchOperation { (workerContext) in
// Cleanup any existing data
let DelAllScheduleLineEntities = NSBatchDeleteRequest(
fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "ScheduleLineEntity")
)
do {
try workerContext.execute(DelAllScheduleLineEntities)
}
catch {
self.alertUserOfFailure(message: "Data load failed.")
}
// Clear local properties
self.schedule = [ScheduleLineEntity]()
// We have to clear data in active contexts after performing batch operations
self.appDelegate.stack.reset()
DispatchQueue.main.async {
self.parseAndSaveSchedule(scheduleRaw)
self.tableView.reloadData()
UserDefaults.standard.set(true, forKey: "hasFetchedSchedule")
UserDefaults.standard.set(NSDate().timeIntervalSince1970, forKey: "lastScheduleFetch")
UserDefaults.standard.synchronize()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
}
}
}
private func parseAndSaveSchedule(_ scheduleRaw: [ScheduleLine]) {
for i in 0 ..< scheduleRaw.count {
let scheduleLineRaw = scheduleRaw[i]
let scheduleLineEntity = ScheduleLineEntity(context: self.appDelegate.stack.context)
scheduleLineEntity.sortKey = Int32(i)
scheduleLineEntity.isSunday = scheduleLineRaw.isSunday
scheduleLineEntity.locality = scheduleLineRaw.locality
var titleString = scheduleLineRaw.dateString + ": "
if let status = scheduleLineRaw.status {
titleString = titleString + status
} else if let localityPretty = scheduleLineRaw.localityPretty {
titleString = titleString + localityPretty
}
scheduleLineEntity.title = titleString
var subtitleString = ""
if let missionaries = scheduleLineRaw.missionaries {
subtitleString = subtitleString + missionaries
}
if scheduleLineRaw.with.count > 0 {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(with "
for i in 0 ..< scheduleLineRaw.with.count {
if i != 0 {
subtitleString = subtitleString + " and "
}
subtitleString = subtitleString + scheduleLineRaw.with[i]
}
subtitleString = subtitleString + ")"
}
if let isAM = scheduleLineRaw.am, let isPM = scheduleLineRaw.pm {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
if isAM && isPM {
subtitleString = subtitleString + "(AM & PM)"
} else if isAM {
subtitleString = subtitleString + "(AM Only)"
} else if isPM {
subtitleString = subtitleString + "(PM Only)"
}
}
if let comment = scheduleLineRaw.comment {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(" + comment + ")"
}
scheduleLineEntity.subtitle = subtitleString
self.schedule.append(scheduleLineEntity)
}
self.appDelegate.stack.save()
}
// MARK: Table View Data Source
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
return schedule.count
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "ScheduleLineTableViewCell"
)!
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
cell.textLabel?.text = scheduleLine.title!
cell.detailTextLabel?.text = scheduleLine.subtitle!
cell.backgroundColor = .white
cell.textLabel?.textColor = Constants.UI.Armadillo
cell.detailTextLabel?.textColor = Constants.UI.Armadillo
if scheduleLine.isSunday {
cell.textLabel?.textColor = .red
cell.detailTextLabel?.textColor = .red
}
return cell
}
override func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
// Only load information if the ScheduleLine refers to a specific locality
guard let key = scheduleLine.locality else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// Protect against missing locality
guard let locality = Directory.directory!.localities[key] else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// If we have location details, load the LocalityView
// Otherwise, jump straight to ContactView
if locality.hasLocationDetails {
let localityViewController = storyboard!.instantiateViewController(
withIdentifier: "LocalityViewController"
) as! LocalityViewController
localityViewController.locality = locality
navigationController!.pushViewController(localityViewController, animated: true)
} else {
let contactViewController = storyboard!.instantiateViewController(
withIdentifier: "ContactViewController"
) as! ContactViewController
contactViewController.locality = locality
navigationController!.pushViewController(contactViewController, animated: true)
}
}
}
|
5fb49468454bc1d0d4428a7a576680f7
| 35.654952 | 111 | 0.560446 | false | false | false | false |
Gitliming/Demoes
|
refs/heads/master
|
Demoes/Demoes/Common/SQLiteManager.swift
|
apache-2.0
|
1
|
//
// SQLiteManager.swift
// Demoes
//
// Created by 张丽明 on 2017/3/12.
// Copyright © 2017年 xpming. All rights reserved.
//
import UIKit
import FMDB
class SQLiteManager: NSObject {
// 工具单例子
static let SQManager:SQLiteManager = SQLiteManager()
var DB:FMDatabase?
var DBQ:FMDatabaseQueue?
override init() {
super.init()
openDB("Demoes_MyNote.sqlite")
}
// 打开数据库
func openDB(_ name:String?){
let path = getCachePath(name!)
print(path)
DB = FMDatabase(path: path)
DBQ = FMDatabaseQueue(path: path)
guard let db = DB else {print("数据库对象创建失败")
return}
if !db.open(){
print("打开数据库失败")
return
}
if creatTable() {
print("创表成功!!!!")
}
}
// 创建数据库
func creatTable() -> Bool{
let sqlit1 = "CREATE TABLE IF NOT EXISTS T_MyNote( \n" +
"stateid INTEGER PRIMARY KEY AUTOINCREMENT, \n" +
"id TEXT, \n" +
"title TEXT, \n" +
"desc TEXT, \n" +
"creatTime TEXT \n" +
");"
//执行语句
return DB!.executeUpdate(sqlit1, withArgumentsIn: nil)
}
//MARK:-- 拼接路径
func getCachePath(_ fileName:String) -> String{
let path1 = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory
, FileManager.SearchPathDomainMask.userDomainMask, true).first
let path2 = path1! + "/" + fileName
return path2
}
}
|
a57d598af572e37612619bfbfa4d2e23
| 25.5 | 103 | 0.554327 | false | false | false | false |
nahive/spotify-notify
|
refs/heads/master
|
SpotifyNotify/Interactors/NotificationsInteractor.swift
|
unlicense
|
1
|
// NotificationsInteractor.swift
// SpotifyNotify
//
// Created by 先生 on 22/02/2018.
// Copyright © 2018 Szymon Maślanka. All rights reserved.
//
import Cocoa
import ScriptingBridge
#if canImport(UserNotifications)
import UserNotifications
#endif
final class NotificationsInteractor {
private let preferences = UserPreferences()
private let spotifyInteractor = SpotifyInteractor()
private var previousTrack: Track?
private var currentTrack: Track?
func showNotification() {
// return if notifications are disabled
guard preferences.notificationsEnabled else {
print("⚠ notification disabled")
return
}
// return if notifications are disabled when in focus
if spotifyInteractor.isFrontmost && preferences.notificationsDisableOnFocus {
print("⚠ spotify is frontmost")
return
}
previousTrack = currentTrack
currentTrack = spotifyInteractor.currentTrack
// return if previous track is same as previous => play/pause and if it's disabled
guard currentTrack != previousTrack || preferences.notificationsPlayPause else {
print("⚠ spotify is changing from play/pause")
return
}
guard spotifyInteractor.isPlaying else {
print("⚠ spotify is not playing")
return
}
// return if current track is nil
guard let currentTrack = currentTrack else {
print("⚠ spotify has no track available")
return
}
// Create and deliver notifications
let viewModel = NotificationViewModel(track: currentTrack,
showSongProgress: preferences.showSongProgress,
songProgress: spotifyInteractor.playerPosition)
createModernNotification(using: viewModel)
}
/// Called by notification delegate
func handleAction() {
spotifyInteractor.nextTrack()
}
// MARK: - Modern Notfications
/// Use `UserNotifications` to deliver the notification in macOS 10.14 and above
@available(OSX 10.14, *)
private func createModernNotification(using viewModel: NotificationViewModel) {
let notification = UNMutableNotificationContent()
notification.title = viewModel.title
notification.subtitle = viewModel.subtitle
notification.body = viewModel.body
notification.categoryIdentifier = NotificationIdentifier.category
// decide whether to add sound
if preferences.notificationsSound {
notification.sound = .default
}
if preferences.showAlbumArt {
addArtwork(to: notification, using: viewModel)
} else {
deliverModernNotification(identifier: viewModel.identifier, content: notification)
}
}
@available(OSX 10.14, *)
private func addArtwork(to notification: UNMutableNotificationContent, using viewModel: NotificationViewModel) {
guard preferences.showAlbumArt else { return }
viewModel.artworkURL?.asyncImage { [weak self] art in
// Create a mutable copy of the downloaded artwork
var artwork = art
// If user wants round album art, then round the image
if self?.preferences.roundAlbumArt == true {
artwork = art?.applyCircularMask()
}
// Save the artwork to the temporary directory
guard let url = artwork?.saveToTemporaryDirectory(withName: "artwork") else { return }
// Add the attachment to the notification
do {
let attachment = try UNNotificationAttachment(identifier: "artwork", url: url)
notification.attachments = [attachment]
} catch {
print("Error creating attachment: " + error.localizedDescription)
}
// remove previous notification and replace it with one with image
DispatchQueue.main.async {
self?.deliverModernNotification(identifier: viewModel.identifier, content: notification)
}
}
}
/// Deliver notifications using `UNUserNotificationCenter`
@available(OSX 10.14, *)
private func deliverModernNotification(identifier: String, content: UNMutableNotificationContent) {
// Create a request
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
let notificationCenter = UNUserNotificationCenter.current()
// Remove delivered notifications
notificationCenter.removeAllDeliveredNotifications()
// Deliver current notification
notificationCenter.add(request)
// remove after userset number of seconds if not taken action
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(preferences.notificationsLength)) {
notificationCenter.removeAllDeliveredNotifications()
}
}
}
|
8e349e5d40f7392ca68296fdb170abd7
| 33.762238 | 116 | 0.659425 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Mac/MainWindow/Timeline/TimelineContainerView.swift
|
mit
|
1
|
//
// TimelineContainerView.swift
// NetNewsWire
//
// Created by Brent Simmons on 2/13/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
final class TimelineContainerView: NSView {
private var contentViewConstraints: [NSLayoutConstraint]?
var contentView: NSView? {
didSet {
if contentView == oldValue {
return
}
if let currentConstraints = contentViewConstraints {
NSLayoutConstraint.deactivate(currentConstraints)
}
contentViewConstraints = nil
oldValue?.removeFromSuperviewWithoutNeedingDisplay()
if let contentView = contentView {
contentView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contentView)
let constraints = constraintsToMakeSubViewFullSize(contentView)
NSLayoutConstraint.activate(constraints)
contentViewConstraints = constraints
}
}
}
}
|
16726a51dd5b36c60922f2c9171eb91c
| 22.594595 | 67 | 0.754868 | false | false | false | false |
antonio081014/LeetCode-CodeBase
|
refs/heads/main
|
Swift/expression-add-operators.swift
|
mit
|
1
|
class Solution {
func addOperators(_ num: String, _ target: Int) -> [String] {
var result = [String]()
let num = Array(num)
func dfs(_ path: String, _ currentIndex: Int, _ value: Int, _ lastValue: Int) {
if currentIndex == num.count {
if value == target {
result.append(path)
}
return
}
var sum = 0
for index in currentIndex ..< num.count {
if num[currentIndex] == Character("0"), index != currentIndex {
return
}
sum = sum * 10 + Int(String(num[index]))!
if currentIndex == 0 {
dfs(path + "\(sum)", index + 1, sum, sum)
} else {
dfs(path + "+\(sum)", index + 1, value + sum, sum)
dfs(path + "-\(sum)", index + 1, value - sum, -sum)
dfs(path + "*\(sum)", index + 1, value - lastValue + lastValue * sum, lastValue * sum)
}
}
}
dfs("", 0, 0, 0)
return result
}
}
|
3ae5cf63374aca938cc6160f9c7a9c2d
| 33.852941 | 106 | 0.396624 | false | false | false | false |
zyhndesign/SDX_DG
|
refs/heads/master
|
sdxdg/sdxdg/MatchListViewController.swift
|
apache-2.0
|
1
|
//
// MatchListViewController.swift
// sdxdg
//
// Created by lotusprize on 16/12/20.
// Copyright © 2016年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON
import AlamofireObjectMapper
class MatchListViewController : UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
var innerClothList:[GarmentModel] = []
var outterClothList:[GarmentModel] = []
var trouserClothList:[GarmentModel] = []
@IBOutlet var innerClothBtn: UIButton!
@IBOutlet var outterClothBtn: UIButton!
@IBOutlet var bottomClothBtn: UIButton!
@IBOutlet var matchCollectionView: UICollectionView!
@IBOutlet var modelView: UIImageView!
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
let clothLayer:UIImageView = UIImageView();
let trousersLayer:UIImageView = UIImageView();
let outClothLayer:UIImageView = UIImageView();
var inClothObject:GarmentModel?
var outClothObject:GarmentModel?
var trouserObject:GarmentModel?
var garmentType:Int = 0
var selectGarmentModelList:[GarmentModel] = []
let refresh = UIRefreshControl.init()
let pageLimit:Int = 10
var inClothPageNum:Int = 0
var outClotPageNum:Int = 0
var trouserPageNum = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
matchCollectionView.register(MatchListCell.self, forCellWithReuseIdentifier:"cell")
matchCollectionView.delegate = self;
matchCollectionView.dataSource = self;
clothLayer.frame = CGRect.init(x: 0, y:0, width: 100, height: 240)
clothLayer.contentMode = UIViewContentMode.scaleAspectFit
outClothLayer.frame = CGRect.init(x: 0, y: 0, width: 100, height: 240)
outClothLayer.contentMode = UIViewContentMode.scaleAspectFit
trousersLayer.frame = CGRect.init(x: 0, y: 00, width: 100, height: 240)
trousersLayer.contentMode = UIViewContentMode.scaleAspectFit
modelView.addSubview(clothLayer)
modelView.addSubview(trousersLayer)
modelView.addSubview(outClothLayer)
refresh.backgroundColor = UIColor.white
refresh.tintColor = UIColor.lightGray
refresh.attributedTitle = NSAttributedString(string:"下拉刷新")
refresh.addTarget(self, action: #selector(refreshLoadingData), for: UIControlEvents.valueChanged)
self.matchCollectionView.addSubview(refresh)
loadCostumeData(category: 0,limit: 10,offset: 0)
NotificationCenter.default.addObserver(self, selector:#selector(self.updateMatchModel(notifaction:)), name: NSNotification.Name(rawValue: "modelMatch"), object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(self.filterMatch(notifaction:)), name: NSNotification.Name(rawValue: "filterMatch"), object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("disppear...")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("view did appear...")
}
func refreshLoadingData(){
if garmentType == 0{
loadCostumeData(category: 0,limit: pageLimit,offset: pageLimit * inClothPageNum)
}
else if garmentType == 1{
loadCostumeData(category: 1,limit: pageLimit,offset: pageLimit * outClotPageNum)
}
else if garmentType == 2{
loadCostumeData(category: 2,limit: pageLimit,offset: pageLimit * trouserPageNum)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
NotificationCenter.default.removeObserver(self)
}
func updateMatchModel(notifaction: NSNotification){
let garmentModel:GarmentModel = (notifaction.object as? GarmentModel)!
if garmentType == 0{
clothLayer.af_setImage(withURL: URL.init(string: garmentModel.imageUrl1!)!)
inClothObject = garmentModel
}
else if garmentType == 1{
outClothLayer.af_setImage(withURL: URL.init(string: garmentModel.imageUrl1!)!)
outClothObject = garmentModel
}
else if garmentType == 2{
trousersLayer.af_setImage(withURL: URL.init(string: garmentModel.imageUrl1!)!)
trouserObject = garmentModel
}
}
func filterMatch(notifaction: NSNotification){
let garmentDataResultModel:GarmentDataResultModel = (notifaction.object as? GarmentDataResultModel)!
if garmentDataResultModel.resultCode == 1{ //内搭
self.innerClothList.removeAll()
let list:[GarmentModel] = garmentDataResultModel.object!
for garmentModel in list{
self.innerClothList.append(garmentModel)
}
self.innerClothSelect()
}
else if garmentDataResultModel.resultCode == 2{ //外套
self.outterClothList.removeAll()
let list:[GarmentModel] = garmentDataResultModel.object!
for garmentModel in list{
self.outterClothList.append(garmentModel)
}
self.outterClothSelect()
}
else if garmentDataResultModel.resultCode == 3{ //下装
self.trouserClothList.removeAll()
let list:[GarmentModel] = garmentDataResultModel.object!
for garmentModel in list{
self.trouserClothList.append(garmentModel)
}
self.bottomClothSelect()
}
self.matchCollectionView.reloadData()
}
//返回多少个组马春
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
//返回多少个cell
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if garmentType == 0{
return innerClothList.count
}
else if garmentType == 1{
return outterClothList.count
}
else if garmentType == 2{
return trouserClothList.count
}
return 0
}
//返回自定义的cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MatchListCell
var garmentModel:GarmentModel?
if garmentType == 0{
garmentModel = innerClothList[indexPath.row]
}
else if garmentType == 1{
garmentModel = outterClothList[indexPath.row]
}
else if garmentType == 2{
garmentModel = trouserClothList[indexPath.row]
}
cell.imgView?.af_setImage(withURL: URL.init(string: (garmentModel?.imageUrl3)!)!)
cell.layer.borderWidth = 0.3
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.titleLabel!.text = garmentModel?.hpName
cell.priceLabel!.text = garmentModel?.price
cell.garmentModel = garmentModel
cell.backgroundColor = UIColor.white
return cell
}
//返回cell 上下左右的间距
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
return UIEdgeInsetsMake(5, 5, 5, 5)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: (screenWidth - 30)/2, height: screenHeight / 2 - 110)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let view:MerchandiseDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "MerchandiseDetailView") as! MerchandiseDetailViewController
var garmentModel:GarmentModel?
if garmentType == 0{
garmentModel = innerClothList[indexPath.row]
}
else if garmentType == 1{
garmentModel = outterClothList[indexPath.row]
}
else if garmentType == 2{
garmentModel = trouserClothList[indexPath.row]
}
view.hpId = (garmentModel?.id)!
self.navigationController?.pushViewController(view, animated: true)
}
@IBAction func popViewBtnClick(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func filterBtnClick(_ sender: Any) {
//self.dismiss(animated: true, completion: {() -> Void in ( print("complete"))})
//self.performSegue(withIdentifier: "filterView", sender: self)
let view = self.storyboard?.instantiateViewController(withIdentifier: "filterView")
self.navigationController?.pushViewController(view!, animated: true)
}
@IBAction func saveBtnClick(_ sender: Any) {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "处理中..."
hud.hide(animated: true, afterDelay: 0.8)
if let cloth = inClothObject{
selectGarmentModelList.append(cloth)
}
else{
hud.label.text = "内搭未选择"
hud.hide(animated: true, afterDelay: 0.8)
return
}
if let cloth = outClothObject{
selectGarmentModelList.append(cloth)
}
else{
hud.label.text = "外套未选择"
hud.hide(animated: true, afterDelay: 0.8)
return
}
if let cloth = trouserObject{
selectGarmentModelList.append(cloth)
}
else{
hud.label.text = "裤子未选择"
hud.hide(animated: true, afterDelay: 0.8)
return
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "BigModelMatch"), object: selectGarmentModelList)
let time: TimeInterval = 1.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
self.navigationController?.popViewController(animated: true)
}
}
@IBAction func innerClothBtn(_ sender: Any) {
self.innerClothSelect()
loadCostumeData(category: 0,limit: 10,offset: 0)
matchCollectionView.reloadData()
}
@IBAction func outterClothBtn(_ sender: Any) {
self.outterClothSelect()
loadCostumeData(category: 1,limit: 10,offset: 0)
matchCollectionView.reloadData()
}
@IBAction func bottomClothBtn(_ sender: Any) {
self.bottomClothSelect()
loadCostumeData(category: 2,limit: 10,offset: 0)
matchCollectionView.reloadData()
}
func innerClothSelect(){
innerClothBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal)
outterClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
bottomClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
garmentType = 0
}
func outterClothSelect(){
outterClothBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal)
innerClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
bottomClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
garmentType = 1
}
func bottomClothSelect(){
bottomClothBtn.setBackgroundImage(UIImage.init(named: "selectedBtn"), for: UIControlState.normal)
innerClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
outterClothBtn.setBackgroundImage(UIImage.init(named: "normalBtn"), for: UIControlState.normal)
garmentType = 2
}
func loadCostumeData(category:Int, limit:Int, offset:Int){
print("loading data.......")
let parameters:Parameters = ["categoryId":category,"limit":limit,"offset":offset]
Alamofire.request(ConstantsUtil.APP_MATCH_LIST_BY_CATEGORY,method:.get, parameters:parameters).responseObject { (response: DataResponse<GarmentDataResultModel>) in
let garmentResponse = response.result.value
if (garmentResponse?.resultCode == 200){
if (category == 0){
if let garmentModelList = garmentResponse?.object {
for garmentModel in garmentModelList{
self.innerClothList.insert(garmentModel, at: 0)
self.inClothPageNum = self.inClothPageNum + 1
}
}
}
else if (category == 1){
if let garmentModelList = garmentResponse?.object {
for garmentModel in garmentModelList{
self.outterClothList.insert(garmentModel, at: 0)
self.outClotPageNum = self.outClotPageNum + 1
}
}
}
else if (category == 2){
if let garmentModelList = garmentResponse?.object {
for garmentModel in garmentModelList{
self.trouserClothList.insert(garmentModel, at: 0)
self.trouserPageNum = self.trouserPageNum + 1
}
}
}
self.matchCollectionView.reloadData()
self.refresh.endRefreshing()
}
}
}
}
|
f820ac997bd9f8c594227a169d4b3920
| 38.505587 | 173 | 0.633812 | false | false | false | false |
project-chip/connectedhomeip
|
refs/heads/master
|
examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissioningViewModel.swift
|
apache-2.0
|
1
|
/**
*
* Copyright (c) 2020-2022 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import os.log
class CommissioningViewModel: ObservableObject {
let Log = Logger(subsystem: "com.matter.casting",
category: "CommissioningViewModel")
@Published var udcRequestSent: Bool?;
@Published var commisisoningWindowOpened: Bool?;
@Published var commisisoningComplete: Bool?;
@Published var connectionSuccess: Bool?;
@Published var connectionStatus: String?;
func prepareForCommissioning(selectedCommissioner: DiscoveredNodeData?) {
if let castingServerBridge = CastingServerBridge.getSharedInstance()
{
castingServerBridge.openBasicCommissioningWindow(DispatchQueue.main,
commissioningWindowRequestedHandler: { (result: Bool) -> () in
DispatchQueue.main.async {
self.commisisoningWindowOpened = result
}
},
commissioningCompleteCallback: { (result: Bool) -> () in
self.Log.info("Commissioning status: \(result)")
DispatchQueue.main.async {
self.commisisoningComplete = result
}
},
onConnectionSuccessCallback: { (videoPlayer: VideoPlayer) -> () in
DispatchQueue.main.async {
self.connectionSuccess = true
self.connectionStatus = "Connected to \(String(describing: videoPlayer))"
self.Log.info("ConnectionViewModel.verifyOrEstablishConnection.onConnectionSuccessCallback called with \(videoPlayer.nodeId)")
}
},
onConnectionFailureCallback: { (error: MatterError) -> () in
DispatchQueue.main.async {
self.connectionSuccess = false
self.connectionStatus = "Failed to connect to video player!"
self.Log.info("ConnectionViewModel.verifyOrEstablishConnection.onConnectionFailureCallback called with \(error)")
}
},
onNewOrUpdatedEndpointCallback: { (contentApp: ContentApp) -> () in
DispatchQueue.main.async {
self.Log.info("CommissioningViewModel.openBasicCommissioningWindow.onNewOrUpdatedEndpointCallback called with \(contentApp.endpointId)")
}
})
}
// Send User directed commissioning request if a commissioner with a known IP addr was selected
if(selectedCommissioner != nil && selectedCommissioner!.numIPs > 0)
{
sendUserDirectedCommissioningRequest(selectedCommissioner: selectedCommissioner)
}
}
private func sendUserDirectedCommissioningRequest(selectedCommissioner: DiscoveredNodeData?) {
if let castingServerBridge = CastingServerBridge.getSharedInstance()
{
castingServerBridge.sendUserDirectedCommissioningRequest(selectedCommissioner!, clientQueue: DispatchQueue.main, udcRequestSentHandler: { (result: Bool) -> () in
self.udcRequestSent = result
})
}
}
}
|
ebf4dee7bd8c9641a3c16229f2c0060f
| 43.655172 | 173 | 0.617761 | false | false | false | false |
eBardX/XestiMonitors
|
refs/heads/master
|
Tests/Mock/MockMotionManager.swift
|
mit
|
1
|
//
// MockMotionManager.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2017-12-31.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
import CoreMotion
@testable import XestiMonitors
internal class MockMotionManager: MotionManagerProtocol {
init() {
self.accelerometerUpdateInterval = 0
self.deviceMotionUpdateInterval = 0
self.gyroUpdateInterval = 0
self.isAccelerometerAvailable = false
self.isDeviceMotionAvailable = false
self.isGyroAvailable = false
self.isMagnetometerAvailable = false
self.magnetometerUpdateInterval = 0
}
var accelerometerUpdateInterval: TimeInterval
var deviceMotionUpdateInterval: TimeInterval
var gyroUpdateInterval: TimeInterval
var magnetometerUpdateInterval: TimeInterval
private(set) var accelerometerData: CMAccelerometerData?
private(set) var deviceMotion: CMDeviceMotion?
private(set) var gyroData: CMGyroData?
private(set) var isAccelerometerAvailable: Bool
private(set) var isDeviceMotionAvailable: Bool
private(set) var isGyroAvailable: Bool
private(set) var isMagnetometerAvailable: Bool
private(set) var magnetometerData: CMMagnetometerData?
func startAccelerometerUpdates(to queue: OperationQueue,
withHandler handler: @escaping CMAccelerometerHandler) {
accelerometerHandler = handler
}
func startDeviceMotionUpdates(using referenceFrame: CMAttitudeReferenceFrame,
to queue: OperationQueue,
withHandler handler: @escaping CMDeviceMotionHandler) {
deviceMotionHandler = handler
}
func startGyroUpdates(to queue: OperationQueue,
withHandler handler: @escaping CMGyroHandler) {
gyroscopeHandler = handler
}
func startMagnetometerUpdates(to queue: OperationQueue,
withHandler handler: @escaping CMMagnetometerHandler) {
magnetometerHandler = handler
}
func stopAccelerometerUpdates() {
accelerometerHandler = nil
}
func stopDeviceMotionUpdates() {
deviceMotionHandler = nil
}
func stopGyroUpdates() {
gyroscopeHandler = nil
}
func stopMagnetometerUpdates() {
magnetometerHandler = nil
}
private var accelerometerHandler: CMAccelerometerHandler?
private var deviceMotionHandler: CMDeviceMotionHandler?
private var gyroscopeHandler: CMGyroHandler?
private var magnetometerHandler: CMMagnetometerHandler?
// MARK: -
func updateAccelerometer(available: Bool) {
isAccelerometerAvailable = available
}
func updateAccelerometer(data: CMAccelerometerData?) {
accelerometerData = data
accelerometerHandler?(data, nil)
}
func updateAccelerometer(error: Error) {
accelerometerData = nil
accelerometerHandler?(nil, error)
}
func updateDeviceMotion(available: Bool) {
isDeviceMotionAvailable = available
}
func updateDeviceMotion(data: CMDeviceMotion?) {
deviceMotion = data
deviceMotionHandler?(data, nil)
}
func updateDeviceMotion(error: Error) {
deviceMotion = nil
deviceMotionHandler?(nil, error)
}
func updateGyroscope(available: Bool) {
isGyroAvailable = available
}
func updateGyroscope(data: CMGyroData?) {
gyroData = data
gyroscopeHandler?(data, nil)
}
func updateGyroscope(error: Error) {
gyroData = nil
gyroscopeHandler?(nil, error)
}
func updateMagnetometer(available: Bool) {
isMagnetometerAvailable = available
}
func updateMagnetometer(data: CMMagnetometerData?) {
magnetometerData = data
magnetometerHandler?(data, nil)
}
func updateMagnetometer(error: Error) {
magnetometerData = nil
magnetometerHandler?(nil, error)
}
}
|
e9958b5083f6fdd55e89d37b2f353a67
| 26.363014 | 91 | 0.672841 | false | false | false | false |
jtsmrd/Intrview
|
refs/heads/master
|
Models/Spotlight.swift
|
mit
|
1
|
//
// Spotlight.swift
// SnapInterview
//
// Created by JT Smrdel on 1/10/17.
// Copyright © 2017 SmrdelJT. All rights reserved.
//
import UIKit
import CloudKit
class Spotlight {
// MARK: Constants
let publicDatabase = CKContainer.default().publicCloudDatabase
let videoStore = (UIApplication.shared.delegate as! AppDelegate).videoStore
// MARK: Variables
var individualProfileCKRecordName: String?
var businessProfileCKRecordName: String?
var cKRecordName: String?
var videoCKRecordName: String?
var videoKey: String?
var jobTitle: String?
var individualName: String?
var businessName: String?
var viewCount: Int = 0
var optionalQuestions = [String]()
var businessNewFlag: Bool = false
var individualNewFlag: Bool = false
var businessDeleteFlag: Bool = false
var individualDeleteFlag: Bool = false
var createDate: Date?
var daysUntilExpired: Int {
get {
let expireDate = createDate?.addingTimeInterval((60 * 60 * 24 * 7))
return Calendar.current.dateComponents([.day], from: Date.init(), to: expireDate!).day!
}
}
var hoursUntilExpired: Int {
get {
let expireDate = createDate?.addingTimeInterval((60 * 60 * 24 * 7))
return Calendar.current.dateComponents([.hour], from: Date.init(), to: expireDate!).hour!
}
}
// MARK: Initializers
/// Default initializer
init() {
}
init(with cloudKitRecord: CKRecord) {
populate(with: cloudKitRecord)
}
init(with cKRecordName: String) {
fetch(with: cKRecordName) { (record, error) in
if let error = error {
print(error)
}
else if let record = record {
self.populate(with: record)
}
}
}
private func populate(with cKRecord: CKRecord) {
self.cKRecordName = cKRecord.recordID.recordName
self.individualProfileCKRecordName = cKRecord.value(forKey: "individualProfileCKRecordName") as? String
self.businessProfileCKRecordName = cKRecord.value(forKey: "businessProfileCKRecordName") as? String
self.videoCKRecordName = cKRecord.value(forKey: "videoCKRecordName") as? String
self.jobTitle = cKRecord.value(forKey: "jobTitle") as? String
self.individualName = cKRecord.value(forKey: "individualName") as? String
self.businessName = cKRecord.value(forKey: "businessName") as? String
self.createDate = cKRecord.object(forKey: "createDate") as? Date
if let viewCount = cKRecord.value(forKey: "viewCount") as? Int {
self.viewCount = viewCount
}
if let newFlag = cKRecord.value(forKey: "businessNewFlag") as? Int {
businessNewFlag = Bool.init(NSNumber(integerLiteral: newFlag))
}
if let newFlag = cKRecord.value(forKey: "individualNewFlag") as? Int {
individualNewFlag = Bool.init(NSNumber(integerLiteral: newFlag))
}
if let deleteFlag = cKRecord.value(forKey: "businessDeleteFlag") as? Int {
businessDeleteFlag = Bool.init(NSNumber(integerLiteral: deleteFlag))
}
if let deleteFlag = cKRecord.value(forKey: "individualDeleteFlag") as? Int {
individualDeleteFlag = Bool.init(NSNumber(integerLiteral: deleteFlag))
}
}
private func fetch(with cKRecordName: String, completion: @escaping ((CKRecord?, Error?) -> Void)) {
let spotlightCKRecordID = CKRecordID(recordName: cKRecordName)
publicDatabase.fetch(withRecordID: spotlightCKRecordID) { (record, error) in
if let error = error {
completion(nil, error)
}
else if let record = record {
completion(record, nil)
}
}
}
private func create(completion: @escaping (() -> Void)) {
let newRecord = CKRecord(recordType: "Spotlight")
let populatedRecord = setCKRecordValues(for: newRecord)
publicDatabase.save(populatedRecord) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
self.cKRecordName = record.recordID.recordName
completion()
}
}
}
private func update(cKRecordName: String, completion: @escaping (() -> Void)) {
fetch(with: cKRecordName) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
let updatedRecord = self.setCKRecordValues(for: record)
self.publicDatabase.save(updatedRecord, completionHandler: { (record, error) in
if let error = error {
print(error)
}
completion()
})
}
}
}
private func setCKRecordValues(for record: CKRecord) -> CKRecord {
record.setValue(self.individualProfileCKRecordName, forKey: "individualProfileCKRecordName")
record.setValue(self.businessProfileCKRecordName, forKey: "businessProfileCKRecordName")
record.setValue(self.videoCKRecordName, forKey: "videoCKRecordName")
record.setValue(self.jobTitle, forKey: "jobTitle")
record.setValue(self.individualName, forKey: "individualName")
record.setValue(self.businessName, forKey: "businessName")
record.setValue(self.viewCount, forKey: "viewCount")
record.setObject(self.createDate as CKRecordValue?, forKey: "createDate")
record.setValue(Int.init(NSNumber(booleanLiteral: businessNewFlag)), forKey: "businessNewFlag")
record.setValue(Int.init(NSNumber(booleanLiteral: individualNewFlag)), forKey: "individualNewFlag")
record.setValue(Int.init(NSNumber(booleanLiteral: businessDeleteFlag)), forKey: "businessDeleteFlag")
record.setValue(Int.init(NSNumber(booleanLiteral: individualDeleteFlag)), forKey: "individualDeleteFlag")
return record
}
func fetchVideo(videoCKRecordName: String, completion: @escaping (() -> Void)) {
let videoCKRecordID = CKRecordID(recordName: videoCKRecordName)
publicDatabase.fetch(withRecordID: videoCKRecordID) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
if let videoAsset = record.object(forKey: "video") as? CKAsset {
let videoURL = videoAsset.fileURL
self.videoKey = record.recordID.recordName + ".mov"
self.videoStore.setVideo(videoURL, forKey: self.videoKey!)
completion()
}
}
}
}
func saveVideo(videoURL: URL, completion: @escaping (() -> Void)) {
let videoRecord = CKRecord(recordType: "Video")
let videoAsset = CKAsset(fileURL: videoURL)
videoRecord.setObject(videoAsset, forKey: "video")
publicDatabase.save(videoRecord) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
self.videoCKRecordName = record.recordID.recordName
self.videoKey = self.videoCKRecordName! + ".mov"
self.videoStore.setVideo(videoURL, forKey: self.videoKey!)
completion()
}
}
}
func forceFetch(with cKRecordName: String, completion: @escaping (() -> Void)) {
fetch(with: cKRecordName) { (record, error) in
if let error = error {
print(error)
completion()
}
else if let record = record {
self.populate(with: record)
completion()
}
}
}
func delete() {
let videoRecordID = CKRecordID(recordName: self.videoCKRecordName!)
publicDatabase.delete(withRecordID: videoRecordID) { (recordID, error) in
if let error = error {
print(error)
}
else {
let spotlightRecordID = CKRecordID(recordName: self.cKRecordName!)
self.publicDatabase.delete(withRecordID: spotlightRecordID, completionHandler: { (recordID, error) in
if let error = error {
print(error)
}
})
}
}
}
func save(completion: @escaping (() -> Void)) {
if let recordName = self.cKRecordName {
update(cKRecordName: recordName, completion: {
completion()
})
}
else {
create(completion: {
completion()
})
}
}
}
|
ec5bef3e6e7f052a9acffd49e302f04e
| 34.860465 | 117 | 0.575443 | false | false | false | false |
XiaHaozheJose/WB
|
refs/heads/master
|
WB/WB/Classes/Main/JS_MainViewController.swift
|
apache-2.0
|
1
|
//
// JS_MainViewController.swift
// WB
//
// Created by 浩哲 夏 on 2017/1/3.
// Copyright © 2017年 浩哲 夏. All rights reserved.
//
import UIKit
class JS_MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addchildViewController(childVC: JS_HomeViewController(), title: "首页", imageName: "tabbar_home")
addchildViewController(childVC: JS_DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
addchildViewController(childVC: JS_MessageViewController(), title: "消息", imageName: "tabbar_message_center")
addchildViewController(childVC: JS_ProfileViewController(), title: "我的", imageName: "tabbar_profile")
changeTabBar()
}
func changeTabBar(){
let tabBar = JS_tabBar()
setValue(tabBar, forKey: "tabBar")
}
private func addchildViewController(childVC : UIViewController , title : String , imageName : String){
let childNavVC = UINavigationController.init(rootViewController: childVC)
addChildViewController(childNavVC)
var imageNormal = UIImage.init(named: imageName)
imageNormal = imageNormal?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
childNavVC.tabBarItem.image = imageNormal
var imageSelected = UIImage.init(named: imageName + "_highlighted")
imageSelected = imageSelected?.withRenderingMode(.alwaysOriginal)
childNavVC.tabBarItem.selectedImage = imageSelected
childNavVC.tabBarItem.title = title
}
}
|
b6a848f678a83761ba0e3f034d2e5881
| 33.75 | 116 | 0.707652 | false | false | false | false |
Mazy-ma/DemoBySwift
|
refs/heads/master
|
CollectionPopView/CollectionPopView/HomeCenterItemCell.swift
|
apache-2.0
|
1
|
//
// HomeCenterItemCell.swift
// CollectionPopView
//
// Created by Mazy on 2017/12/15.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class HomeCenterItemCell: UICollectionViewCell {
var contentText: String? {
didSet {
contentLabel.text = contentText
}
}
private lazy var contentLabel: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
backgroundColor = .randomColor()
layer.cornerRadius = 8
contentLabel.frame = self.bounds
contentLabel.textAlignment = .center
contentLabel.font = UIFont.boldSystemFont(ofSize: 88)
addSubview(contentLabel)
}
}
|
4e206258ef06f8bf2685797cb3ac9fa8
| 21.2 | 61 | 0.613739 | false | false | false | false |
panyam/SwiftHTTP
|
refs/heads/master
|
Sources/Handlers/Router.swift
|
apache-2.0
|
2
|
//
// Router.swift
// SwiftHTTP
//
// Created by Sriram Panyam on 12/25/15.
// Copyright © 2015 Sriram Panyam. All rights reserved.
//
import Foundation
public typealias HeaderNameValuePair = (name: String, value: String)
//public class MatchResult
//{
// var route : Route?
// var variables : [String : AnyObject] = [String : AnyObject]()
// var handler : HttpRequestHandler?
//}
//
///**
// * Matcher objects
// */
//public protocol Matcher
//{
// func match(request: HttpRequest, _ result: MatchResult) -> Bool
//}
//
//public class HostMatcher
//{
//}
//
//public class QueryParamMatcher
//{
// /**
// * Matched based on query parameters
// */
// func match(request: HttpRequest, _ result: MatchResult) -> Bool
// {
// }
//}
//
///**
// * Returns a http handler method for a given request.
// */
//public class Router : RouteMatcher
//{
// var routes : [Route] = [Route]()
//
// public init()
// {
// }
//
// public func match(request: HttpRequest, _ result: MatchResult) -> Bool {
// for route in routes {
// if route.match(request, result) {
// return true
// }
// }
// return false
// }
//
// public func handler() -> HttpRequestHandler
// {
// return {(request, response) in
// }
// }
//}
//public class Route : RouteMatcher
//{
// /**
// * Optional name of the route
// */
// var name : String = ""
//
// /**
// */
// private (set) var parentRoute : Route?
// var matchers : [RouteMatcher] = [RouteMatcher]()
//
// public convenience init()
// {
// self.init("", nil)
// }
//
// public init(_ name: String, _ parent : Route?)
// {
// name = n
// parentRoute = parent
// }
//
// func match(request: HttpRequest, result: MatchResult) -> Bool
// {
// for matcher in matchers {
// if matcher.match(reqeust, result: result)
// }
// }
//
// public func Methods(methods: String...) -> Route {
// matchers.append {(request: HttpRequest) -> Bool in
// for method in methods {
// if methods.contains(method) {
// return true
// }
// }
// return false
// }
// return Route(self)
// }
//
// public func Header(values: HeaderNameValuePair...) -> Route {
// matchers.append {(request: HttpRequest) -> Bool in
// for (name, value) in values {
// if let headerValue = request.headers.forKey(name)?.values.first
// {
// if headerValue != value
// {
// return false
// }
// } else {
// return false
// }
// }
// return true
// }
// return Route(self)
// }
//}
|
1db160d4c7ca79423318f6858f3672a3
| 22.102362 | 81 | 0.489775 | false | false | false | false |
coolshubh4/iOS-Demos
|
refs/heads/master
|
Click Counter/Click Counter/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Click Counter
//
// Created by Shubham Tripathi on 12/07/15.
// Copyright (c) 2015 Shubham Tripathi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var count = 0
var label:UILabel!
var toggle = true
var colorOne = UIColor.yellowColor()
var colorTwo = UIColor.redColor()
var colorArray = [UIColor.yellowColor(), UIColor.redColor(), UIColor.purpleColor(), UIColor.orangeColor()]
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = UIColor.cyanColor()
//Label
var label = UILabel()
label.frame = CGRectMake(100, 150, 60, 60)
label.text = "0"
self.view.addSubview(label)
self.label = label
//Increment Button
var incrementButton = UIButton()
incrementButton.frame = CGRectMake(100, 250, 60, 60)
incrementButton.setTitle("Inc +", forState: .Normal)
incrementButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(incrementButton)
incrementButton.addTarget(self, action: "incrementCount", forControlEvents: UIControlEvents.TouchUpInside)
//Decrement Button
var decrementButton = UIButton()
decrementButton.frame = CGRectMake(100, 350, 60, 60)
decrementButton.setTitle("Dec -", forState: .Normal)
decrementButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(decrementButton)
decrementButton.addTarget(self, action: "decrementCount", forControlEvents: UIControlEvents.TouchUpInside)
//BackgroungColorToggle Button
var toggleColorButton = UIButton()
toggleColorButton.frame = CGRectMake(100, 450, 150, 100)
toggleColorButton.setTitle("ToggleBGColor", forState: .Normal)
toggleColorButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(toggleColorButton)
toggleColorButton.addTarget(self, action: "toggleBGColor", forControlEvents: UIControlEvents.TouchUpInside)
}
func incrementCount() {
self.count++
self.label.text = "\(self.count)"
}
func decrementCount() {
self.count--
self.label.text = "\(self.count)"
}
func toggleBGColor () {
// if toggle {
// self.view.backgroundColor = colorOne
// toggle = false
// } else {
// self.view.backgroundColor = colorTwo
// toggle = true
// }
let randomColor = Int(arc4random_uniform(UInt32(colorArray.count)))
print(randomColor)
self.view.backgroundColor = colorArray[randomColor]
}
}
|
a3ce58eae88569fdba6db2bc32c25a64
| 31.482759 | 115 | 0.62845 | false | false | false | false |
box/box-ios-sdk
|
refs/heads/main
|
Sources/Modules/AuthModuleDispatcher.swift
|
apache-2.0
|
1
|
//
// AuthModuleDispatcher.swift
// BoxSDK
//
// Created by Daniel Cech on 13/06/2019.
// Copyright © 2019 Box. All rights reserved.
//
import Foundation
class AuthModuleDispatcher {
let authQueue = ThreadSafeQueue<AuthActionTuple>(completionQueue: DispatchQueue.main)
var active = false
static var current = 1
func start(action: @escaping AuthActionClosure) {
let currentId = AuthModuleDispatcher.current
AuthModuleDispatcher.current += 1
authQueue.enqueue((id: currentId, action: action)) {
if !self.active {
self.active = true
self.processAction()
}
}
}
func processAction() {
authQueue.dequeue { [weak self] action in
if let unwrappedAction = action {
unwrappedAction.action {
self?.processAction()
}
}
else {
self?.active = false
}
}
}
}
|
4094c9f5eb171f0059ed507859c13537
| 22.857143 | 89 | 0.558882 | false | false | false | false |
AndreyBaranchikov/Keinex-iOS
|
refs/heads/master
|
Keinex/Defaults.swift
|
mit
|
1
|
//
// Defaults.swift
// Keinex
//
// Created by Андрей on 07.08.16.
// Copyright © 2016 Keinex. All rights reserved.
//
import Foundation
import UIKit
let userDefaults = UserDefaults.standard
let isiPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
let latestPostValue = "postValue"
//Sources
let sourceUrl:NSString = "SourceUrlDefault"
let sourceUrlKeinexRu:NSString = "https://keinex.ru/wp-json/wp/v2/posts/"
let sourceUrlKeinexCom:NSString = "http://keinex.com/wp-json/wp/v2/posts/"
let autoDelCache:NSString = "none"
|
3b599d5866541f4326ab1ce3863bf6db
| 26.4 | 76 | 0.757299 | false | false | false | false |
CoderXiaoming/Ronaldo
|
refs/heads/master
|
SaleManager/SaleManager/ComOperation/Model/SAMSaleOrderInfoModel.swift
|
apache-2.0
|
1
|
//
// SAMSaleOrderInfoModel.swift
// SaleManager
//
// Created by apple on 16/12/7.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
class SAMSaleOrderInfoModel: NSObject {
///销售日期
var startDate = "" {
didSet{
startDate = ((startDate == "") ? "---" : startDate)
}
}
///销售金额
var actualMoney = 0.0
///客户名称
var CGUnitName = "" {
didSet{
CGUnitName = ((CGUnitName == "") ? "---" : CGUnitName)
}
}
///销售单号
var billNumber = "" {
didSet{
billNumber = ((billNumber == "") ? "---" : billNumber)
}
}
//MARK: - 辅助属性
let orderStateImageName = "indicater_saleHistory_selected"
}
|
d00d9a3aeee3579217ba91b7dc888cbd
| 19.222222 | 66 | 0.508242 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
refs/heads/master
|
Objects/data types/enumerable/CMGiftPokemon.swift
|
gpl-2.0
|
1
|
//
// CMGiftPokemon.swift
// Colosseum Tool
//
// Created by The Steez on 16/08/2018.
//
import Foundation
var kPlusleOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F514
case .JP: return 0x14A83C
case .EU: return 0x150DD8
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D9C8
case .JP: return 0x12B098
case .EU: return 0x131BF4
case .OtherGame: return 0
}
}
}
var kHoohOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F430
case .JP: return 0x14A758
case .EU: return 0x150CF4
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D8E4
case .JP: return 0x12AFB8
case .EU: return 0x131B10
case .OtherGame: return 0
}
}
}
var kCelebiOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F200
case .JP: return 0x14A528
case .EU: return 0x150AC4
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D6B4
case .JP: return 0x12ADD0
case .EU: return 0x1318E0
case .OtherGame: return 0
}
}
}
var kPikachuOffset: Int {
if game == .XD {
switch region {
case .US: return 0x14F310
case .JP: return 0x14A638
case .EU: return 0x150BD4
case .OtherGame: return 0
}
} else {
switch region {
case .US: return 0x12D7C4
case .JP: return 0x12AEBC
case .EU: return 0x1319F0
case .OtherGame: return 0
}
}
}
let kDistroPokemonSpeciesOffset = 0x02
let kDistroPokemonLevelOffset = 0x07
let kDistroPokemonShininessOffset = 0x5A
let kDukingsPlusleshininessOffset = 0x66
let kNumberOfDistroPokemon = 4
final class CMGiftPokemon: NSObject, XGGiftPokemon, GoDCodable {
var index = 0
var level = 0x0
var species = XGPokemon.index(0)
var move1 = XGMoves.index(0)
var move2 = XGMoves.index(0)
var move3 = XGMoves.index(0)
var move4 = XGMoves.index(0)
var giftType = ""
// unused
var exp = -1
var shinyValue = XGShinyValues.random
private(set) var gender = XGGenders.random
private(set) var nature = XGNatures.random
var usesLevelUpMoves = true
var startOffset : Int {
get {
switch index {
case 0 : return kPlusleOffset
case 1 : return kHoohOffset
case 2 : return kCelebiOffset
default: return kPikachuOffset
}
}
}
init(index: Int) {
super.init()
let dol = XGFiles.dol.data!
self.index = index
let start = startOffset
let species = dol.get2BytesAtOffset(start + kDistroPokemonSpeciesOffset)
self.species = .index(species)
level = dol.getByteAtOffset(start + kDistroPokemonLevelOffset)
let shiny = dol.get2BytesAtOffset(start + (index == 0 ? kDukingsPlusleshininessOffset : kDistroPokemonShininessOffset))
self.shinyValue = XGShinyValues(rawValue: shiny) ?? .random
let moves = self.species.movesForLevel(level)
self.move1 = moves[0]
self.move2 = moves[1]
self.move3 = moves[2]
self.move4 = moves[3]
switch index {
case 0 : self.giftType = "Duking's Plusle"
case 1 : self.giftType = "Mt.Battle Ho-oh"
case 2 : self.giftType = "Agate Celebi"
default : self.giftType = "Agate Pikachu"
}
}
func save() {
let dol = XGFiles.dol.data!
let start = startOffset
dol.replaceByteAtOffset(start + kDistroPokemonLevelOffset, withByte: level)
dol.replace2BytesAtOffset(start + kDistroPokemonSpeciesOffset, withBytes: species.index)
dol.replace2BytesAtOffset(start + (index == 0 ? kDukingsPlusleshininessOffset : kDistroPokemonShininessOffset), withBytes: shinyValue.rawValue)
dol.save()
}
}
extension CMGiftPokemon: XGEnumerable {
var enumerableName: String {
return species.name.string
}
var enumerableValue: String? {
return index.string
}
static var className: String {
return game == .XD ? "Colosseum Gift Pokemon" : "Gift Pokemon"
}
static var allValues: [CMGiftPokemon] {
var values = [CMGiftPokemon]()
for i in 0 ... 3 {
values.append(CMGiftPokemon(index: i))
}
return values
}
}
extension CMGiftPokemon: XGDocumentable {
var documentableName: String {
return (enumerableValue ?? "") + " - " + enumerableName
}
static var DocumentableKeys: [String] {
return ["index", "name", "level", "gender", "nature", "shininess", "moves"]
}
func documentableValue(for key: String) -> String {
switch key {
case "index":
return index.string
case "name":
return species.name.string
case "level":
return level.string
case "gender":
return gender.string
case "nature":
return nature.string
case "shininess":
return shinyValue.string
case "moves":
var text = ""
text += "\n" + move1.name.string
text += "\n" + move2.name.string
text += "\n" + move3.name.string
text += "\n" + move4.name.string
return text
default:
return ""
}
}
}
|
32a61995830c90469f6e64c83afcf809
| 20.858447 | 145 | 0.680593 | false | false | false | false |
aitorbf/Curso-Swift
|
refs/heads/master
|
Is It Prime/Is It Prime/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Is It Prime
//
// Created by Aitor Baragaño Fernández on 22/9/15.
// Copyright © 2015 Aitor Baragaño Fernández. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var number: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func buttonPressed(sender: AnyObject) {
let numberInt = Int(number.text!)
if numberInt != nil {
let unwrappedNumber = numberInt!
resultLabel.textColor = UIColor.blackColor()
var isPrime = true;
if unwrappedNumber == 1 {
isPrime = false
}
if unwrappedNumber != 2 && unwrappedNumber != 1 {
for var i = 2; i < unwrappedNumber; i++ {
if unwrappedNumber % i == 0 {
isPrime = false;
}
}
}
if isPrime == true {
resultLabel.text = "\(unwrappedNumber) is prime!"
} else {
resultLabel.text = "\(unwrappedNumber) is not prime!"
}
} else {
resultLabel.textColor = UIColor.redColor()
resultLabel.text = "Please enter a number in the box"
}
number.resignFirstResponder()
}
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.
}
}
|
e3a97e2c232b99c81502288680290bc0
| 24.0625 | 80 | 0.450374 | false | false | false | false |
einsteinx2/iSub
|
refs/heads/master
|
Classes/Server Loading/Loaders/CreatePlaylistLoader.swift
|
gpl-3.0
|
1
|
//
// CreatePlaylistLoader.swift
// iSub Beta
//
// Created by Felipe Rolvar on 26/11/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
class CreatePlaylistLoader: ApiLoader, ItemLoader {
private var songs = [Song]()
var playlistName: String
var items: [Item] {
return songs
}
var associatedItem: Item? {
return PlaylistRepository.si.playlist(name: playlistName, serverId: serverId)
}
init(with name: String, and serverId: Int64) {
self.playlistName = name
super.init(serverId: serverId)
}
override func createRequest() -> URLRequest? {
return URLRequest(subsonicAction: .createPlaylist,
serverId: serverId,
parameters: ["name": playlistName,
"songId" : items.map { $0.itemId }])
}
override func processResponse(root: RXMLElement) -> Bool {
songs.removeAll()
root.iterate("playlist.entry") { [weak self] in
guard let serverId = self?.serverId,
let song = Song(rxmlElement: $0, serverId: serverId) else {
return
}
self?.songs.append(song)
}
return true
}
@discardableResult func loadModelsFromDatabase() -> Bool {
guard let playlist = associatedItem as? Playlist else { return false }
playlist.loadSubItems()
songs = playlist.songs
return songs.count > 0
}
// MARK: - Nothing to implement
func persistModels() { }
}
|
60c61bcb856e10a3f52f8f37ec60676f
| 27.333333 | 85 | 0.573994 | false | false | false | false |
brokenseal/iOS-exercises
|
refs/heads/master
|
FaceSnap/FaceSnap/FilteredImageBuilder.swift
|
mit
|
1
|
//
// FilteredImageBuilder.swift
// FaceSnap
//
// Created by Davide Callegari on 28/06/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import Foundation
import CoreImage
import UIKit
private struct PhotoFilter {
static let ColorClamp = "CIColorClamp"
static let ColorControls = "CIColorControls"
static let PhotoEffectIstant = "CIPhotoEffectInstant"
static let PhotoEffectProcess = "CIPhotoEffectProcess"
static let PhotoEffectNoir = "CIPhotoEffectNoir"
static let Sepia = "CISepiaTone"
static func defaultFilters() -> [CIFilter] {
let colorClamp = CIFilter(name: self.ColorClamp)!
colorClamp.setValue(CIVector(x: 0.2, y: 0.2, z: 0.2, w: 0.2), forKey: "inputMinComponents")
colorClamp.setValue(CIVector(x: 0.9, y: 0.9, z: 0.9, w: 0.9), forKey: "inputMaxComponents")
let colorControls = CIFilter(name: self.ColorControls)!
colorControls.setValue(0.1, forKey: kCIInputSaturationKey)
let sepia = CIFilter(name: self.Sepia)!
sepia.setValue(0.7, forKey: kCIInputIntensityKey)
return [
colorClamp,
colorControls,
CIFilter(name: self.PhotoEffectIstant)!,
CIFilter(name: self.PhotoEffectProcess)!,
CIFilter(name: self.PhotoEffectNoir)!,
sepia,
]
}
}
final class FilteredImageBuilder {
private let inputImage: UIImage
init(image: UIImage){
self.inputImage = image
}
func imageWithDefaultFilters() -> [UIImage]{
return image(withFilters: PhotoFilter.defaultFilters())
}
func image(withFilters filters: [CIFilter]) -> [UIImage]{
return filters.map { image(self.inputImage, withFilter: $0) }
}
func image(_ image: UIImage, withFilter filter: CIFilter) -> UIImage {
let inputImage = image.ciImage ?? CIImage(image: image)!
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage = filter.outputImage!
return UIImage(ciImage: outputImage)
}
}
|
43de28b0c856cf875c7452e6251d2ebf
| 31.153846 | 99 | 0.649761 | false | false | false | false |
lionchina/RxSwiftBook
|
refs/heads/master
|
RxTableViewWithSection/RxTableViewWithSection/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// RxTableViewWithSection
//
// Created by MaxChen on 04/08/2017.
// Copyright © 2017 com.linglustudio. All rights reserved.
//
import Foundation
import UIKit
import RxCocoa
import RxSwift
import RxDataSources
class ViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var tableviewData: UITableView!
let disposeBag = DisposeBag()
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>()
override func viewDidLoad() {
super.viewDidLoad()
let dataSource = self.dataSource
let items = Observable.just([
SectionModel(model: "First section", items: [1.0, 2.0, 3.0]),
SectionModel(model: "Second section", items: [2.0, 3.0, 4.0]),
SectionModel(model: "Third section", items: [3.0, 4.0, 5.0])])
dataSource.configureCell = { (_, tv, indexPath, element) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(element) @ row \(indexPath.row)"
return cell
}
dataSource.titleForHeaderInSection = { dataSource, sectionIndex in
return dataSource[sectionIndex].model
}
items.bind(to: tableviewData.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableviewData.rx.itemSelected
.map { indexPath in
return (indexPath, dataSource[indexPath])
}
.subscribe(onNext: { indexPath, model in
print("Tapped \(model) @ row \(indexPath)")
})
.disposed(by: disposeBag)
tableviewData.rx.setDelegate(self).disposed(by: disposeBag)
}
}
|
c0819d1399d90c1d32e095eae505e456
| 33.74 | 89 | 0.62464 | false | false | false | false |
GTMYang/GTMRefresh
|
refs/heads/master
|
GTMRefreshExample/Default/DefaultCollectionViewController.swift
|
mit
|
1
|
//
// DefaultCollectionViewController.swift
// PullToRefreshKit
//
// Created by luoyang on 2016/12/8.
// Copyright © 2016年 luoyang. All rights reserved.
//
import Foundation
import UIKit
class DefaultCollectionViewController:UIViewController,UICollectionViewDataSource{
var collectionView:UICollectionView?
override func viewDidLoad() {
self.view.backgroundColor = UIColor.white
self.setUpCollectionView()
self.collectionView?.gtm_addRefreshHeaderView {
[weak self] in
print("excute refreshBlock")
self?.refresh()
}
self.collectionView?.gtm_addLoadMoreFooterView {
[weak self] in
print("excute loadMoreBlock")
self?.loadMore()
}
}
// MARK: Test
func refresh() {
perform(#selector(endRefresing), with: nil, afterDelay: 3)
}
@objc func endRefresing() {
self.collectionView?.endRefreshing(isSuccess: true)
}
func loadMore() {
perform(#selector(endLoadMore), with: nil, afterDelay: 3)
}
@objc func endLoadMore() {
self.collectionView?.endLoadMore(isNoMoreData: true)
}
func setUpCollectionView(){
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = UICollectionView.ScrollDirection.vertical
flowLayout.itemSize = CGSize(width: 100, height: 100)
self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
self.collectionView?.backgroundColor = UIColor.white
self.collectionView?.dataSource = self
self.view.addSubview(self.collectionView!)
self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 21
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = UIColor.lightGray
return cell
}
deinit{
print("Deinit of DefaultCollectionViewController")
}
}
|
99f32624adaf92342c0e923d0b720bcd
| 31.5 | 121 | 0.665812 | false | false | false | false |
igerry/ProjectEulerInSwift
|
refs/heads/master
|
ProjectEulerInSwift/Euler/Problem6.swift
|
apache-2.0
|
1
|
import Foundation
/*
Sum square difference
Problem 6
25164150
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
*/
class Problem6 {
func solution() -> Int {
var sum = 0
var sumSquare = 0
for i in 1...100 {
sum += i
sumSquare += i * i
}
let diff = sum * sum - sumSquare
return diff
}
}
|
5829cd1abb884a0cc4a3208276c5b2c6
| 22.818182 | 133 | 0.597964 | false | false | false | false |
abreis/swift-gissumo
|
refs/heads/master
|
scripts/parsers/singles/averageColumn.swift
|
mit
|
1
|
/* This script takes a list of statistical data files containing tab-separated values,
* where the first column is a time entry. It then gathers the data in the column
* specified in the second argument and returns an average value.
*
* If a time value is provided as the second argument, only samples that
* occur after that time are recorded.
*/
import Foundation
/*** MEASUREMENT SWIFT3 ***/
// A measurement object: load data into 'samples' and all metrics are obtained as computed properties
struct Measurement {
var samples = [Double]()
mutating func add(point: Double) { samples.append(point) }
var count: Double { return Double(samples.count) }
var sum: Double { return samples.reduce(0,+) }
var mean: Double { return sum/count }
var min: Double { return samples.min()! }
var max: Double { return samples.max()! }
// This returns the maximum likelihood estimator(over N), not the minimum variance unbiased estimator (over N-1)
var variance: Double { return samples.reduce(0,{$0 + pow($1-mean,2)} )/count }
var stdev: Double { return sqrt(variance) }
// Specify the desired confidence level (1-significance) before requesting the intervals
// func confidenceIntervals(confidence: Double) -> Double {}
//var confidence: Double = 0.90
//var confidenceInterval: Double { return 0.0 }
}
/*** ***/
guard 3...4 ~= CommandLine.arguments.count else {
print("usage: \(CommandLine.arguments[0]) [list of data files] [column name or number] [minimum time]")
exit(EXIT_FAILURE)
}
var columnNumber: Int? = nil
var cliColName: String? = nil
if let cliColNum = UInt(CommandLine.arguments[2]) {
columnNumber = Int(cliColNum)-1
} else {
cliColName = CommandLine.arguments[2]
}
// Load minimum sample time
var minTime: Double = 0.0
if CommandLine.arguments.count == 4 {
guard let inMinTime = Double(CommandLine.arguments[3]) else {
print("Error: Invalid minimum time specified.")
exit(EXIT_FAILURE)
}
minTime = inMinTime
}
var statFiles: String
do {
let statFilesURL = NSURL.fileURL(withPath: CommandLine.arguments[1])
_ = try statFilesURL.checkResourceIsReachable()
statFiles = try String(contentsOf: statFilesURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
// Process statistics files
var dataMeasurement = Measurement()
for statFile in statFiles.components(separatedBy: .newlines).filter({!$0.isEmpty}) {
// 1. Open and read the statFile into a string
var statFileData: String
do {
let statFileURL = NSURL.fileURL(withPath: statFile)
_ = try statFileURL.checkResourceIsReachable()
statFileData = try String(contentsOf: statFileURL, encoding: String.Encoding.utf8)
} catch {
print(error)
exit(EXIT_FAILURE)
}
// 2. Break the stat file into lines
var statFileLines: [String] = statFileData.components(separatedBy: .newlines).filter({!$0.isEmpty})
// [AUX] For the very first file, if a column name was specified instead of a column number, find the column number by name.
if columnNumber == nil {
let header = statFileLines.first!
let colNames = header.components(separatedBy: "\t").filter({!$0.isEmpty})
guard let colIndex = colNames.index(where: {$0 == cliColName})
else {
print("ERROR: Can't match column name to a column number.")
exit(EXIT_FAILURE)
}
columnNumber = colIndex
}
// 3. Drop the first line (header)
statFileLines.removeFirst()
// 4. Run through the statFile lines
for statFileLine in statFileLines {
// Split each line by tabs
let statFileLineColumns = statFileLine.components(separatedBy: "\t").filter({!$0.isEmpty})
// First column is time index for the dictionary
// 'columnNumber' column is the data we want
guard let timeEntry = Double(statFileLineColumns[0]),
let dataEntry = Double(statFileLineColumns[columnNumber!]) else {
print("ERROR: Can't interpret time and/or data.")
exit(EXIT_FAILURE)
}
// Push the data into the measurement's samples
if(timeEntry>minTime) {
dataMeasurement.add(point: dataEntry)
}
}
}
// For each sorted entry in the dictionary, print out the mean, median, min, max, std, var, etcetera
print("mean", "count", separator: "\t")
print(dataMeasurement.mean, dataMeasurement.count, separator: "\t")
|
9fd004d783475c2f3cde51b67c8fb720
| 32.173228 | 125 | 0.723 | false | false | false | false |
Ryukie/Ryubo
|
refs/heads/master
|
Ryubo/Ryubo/Classes/Model/RYUser.swift
|
mit
|
1
|
//
// RYUser.swift
// Ryubo
//
// Created by 王荣庆 on 16/2/16.
// Copyright © 2016年 Ryukie. All rights reserved.
//
import UIKit
class RYUser: NSObject {
///用户id
var id: Int64 = 0
///用户名称
var name: String?
///用户头像地址(中图),50×50像素
var profile_image_url: String?
//计算用户头像的url地址
var headImageURL: NSURL? {
return NSURL(string: profile_image_url ?? "")
}
/// 认证类型,-1:没有认证,0,认证用户,2,3,5: 企业认证,220: 达人 草根
var verified_type: Int = -1
var verified_type_image: UIImage? {
switch verified_type {
case -1: return nil
case 0: return UIImage(named: "avatar_vip")
case 2,3,5: return UIImage(named: "avatar_enterprise_vip")
case 220: return UIImage(named: "avatar_grassroot")
default : return nil
}
}
/// 会员等级 0-6
var mbrank: Int = 0
var mbrank_image: UIImage? {
if mbrank > 0 && mbrank < 7 {
return UIImage(named: "common_icon_membership_level\(mbrank)")
}
return nil
}
init(dict:[String : AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
//重写对象的描述信息
override var description: String {
//使用kvc方式 获取对象 的字典信息
let keys = ["name","id","profile_image_url","mbrank","verified_type"]
let dict = self.dictionaryWithValuesForKeys(keys)
return dict.description
}
}
|
6e774d9b7977a99b52de7e7645c1a54c
| 24.913793 | 77 | 0.581504 | false | false | false | false |
buscarini/JMSSwiftParse
|
refs/heads/master
|
Tests/helpers.swift
|
mit
|
1
|
//
// helpers.swift
// JMSSwiftParse
//
// Created by Jose Manuel Sánchez Peñarroja on 19/11/14.
// Copyright (c) 2014 José Manuel Sánchez. All rights reserved.
//
import Foundation
public class TestClass {
var requiredString = ""
var optionalString : String?
var email = ""
var requiredUrl : NSURL = NSURL(string : "blah")!
var optionalUrl : NSURL? = NSURL()
var requiredBool = false
var optionalBool : Bool?
var availableString = ""
var requiredInt = 0
var optionalInt : Int? = 0
var requiredDouble = 0.0
var optionalDouble : Double? = 0.0
var date = NSDate()
public init() {
}
}
|
e484fa56571e472f9e3777386ab94e61
| 18.709677 | 64 | 0.679214 | false | false | false | false |
Tarovk/Mundus_Client
|
refs/heads/master
|
Aldo/Aldo.swift
|
mit
|
2
|
//
// Aldo.swift
// Pods
//
// Created by Team Aldo on 29/12/2016.
//
//
import Foundation
import Alamofire
/**
All core URI requests that are being processed by the Aldo Framework.
*/
public enum RequestURI: String {
/// Dummy URI.
case REQUEST_EMPTY = "/"
/// URI to request and authorization token.
case REQUEST_AUTH_TOKEN = "/token"
/// URI template to create a session.
case SESSION_CREATE = "/session/username/%@"
/// URI template to join a session.
case SESSION_JOIN = "/session/join/%@/username/%@"
/// URI to get the information about the session.
case SESSION_INFO = "/session"
/// URI to get the players that have joined the session.
case SESSION_PLAYERS = "/session/players"
/// URI to resume the session.
case SESSION_STATE_PLAY = "/session/play"
/// URI to pause the session.
case SESSION_STATE_PAUSE = "/session/pause"
/// URI to stop and delete the session.
case SESSION_DELETE = "/session/delete"
/// URI to get all players linked to the device.
case PLAYER_ALL = "/player/all"
/// URI to get information of the active player.
case PLAYER_INFO = "/player"
/// URI template to update the username of the active player.
case PLAYER_USERNAME_UPDATE = "/player/username/%@"
/**
Converts the rawValue to one containing regular expression for comparison.
- Returns: A *String* representation as regular expression.
*/
public func regex() -> String {
var regex: String = "(.)+?"
if self == .PLAYER_USERNAME_UPDATE {
regex = "(.)+?$"
}
return "\(self.rawValue.replacingOccurrences(of: "%@", with: regex))$"
}
}
/**
Protocol for sending a request to the Aldo Framework.
*/
public protocol AldoRequester {
/**
Senda a request to the server running the Aldo Framework.
- Parameters:
- uri: The request to be send.
- method: The HTTP method to be used for the request.
- parameters: The information that should be passed in the body
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
static func request(uri: String, method: HTTPMethod, parameters: Parameters, callback: Callback?)
}
/**
Class containing static methods to communicate with the Aldo Framework.
*/
public class Aldo: AldoRequester {
/// Keys for data storage
public enum Keys: String {
case AUTH_TOKEN
case SESSION
}
static let storage = UserDefaults.standard
static var hostAddress: String = "127.0.0.1"
static var baseAddress: String = "127.0.0.1"
static let id: String = UIDevice.current.identifierForVendor!.uuidString
/**
Define the address of the server running the Aldo Framework.
- Parameters:
- address: the address of the server running the Aldo Framework
including port and **without** a / at the end.
*/
public class func setHostAddress(address: String) {
if let url = URL(string: address) {
let host = url.host != nil ? url.host! : address
let port = url.port != nil ? ":\(url.port!)" : ""
hostAddress = address
baseAddress = "\(host)\(port)"
}
//hostAddress.asURL().s
//baseAddress =
}
/**
Checks whether the device already has an authorization token or not.
- Returns: *true* if having a token, otherwise *false*.
*/
public class func hasAuthToken() -> Bool {
return storage.object(forKey: Keys.AUTH_TOKEN.rawValue) != nil
}
/**
Checks wether the device has a information about a player in a session.
- Returns: *true* if having information about a player, otherwise *false*.
*/
public class func hasActivePlayer() -> Bool {
return storage.object(forKey: Keys.SESSION.rawValue) != nil
}
/**
Retrieves the storage where the information retrieved from the Aldo Framework is stored.
- Returns: an instance of *UserDefaults*
*/
public class func getStorage() -> UserDefaults {
return storage
}
/**
Retrieves the stored information about an active player.
- Returns: an instance of *Player* if available, otherwise *nil*
*/
public class func getPlayer() -> Player? {
if let objSession = storage.object(forKey: Keys.SESSION.rawValue) {
let sessionData = objSession as! Data
let session: Player = NSKeyedUnarchiver.unarchiveObject(with: sessionData) as! Player
return session
}
return nil
}
/// Stores information about an active player.
public class func setPlayer(player: Player) {
let playerData: Data = NSKeyedArchiver.archivedData(withRootObject: player)
Aldo.getStorage().set(playerData, forKey: Aldo.Keys.SESSION.rawValue)
}
/// Helper method creating the value of the Authorization header used for a request.
class func getAuthorizationHeaderValue() -> String {
let objToken = storage.object(forKey: Keys.AUTH_TOKEN.rawValue)
let token: String = (objToken != nil) ? ":\(objToken as! String)" : ""
var playerId: String = ""
if let player = Aldo.getPlayer() {
playerId = ":\(player.getId())"
}
return "\(id)\(token)\(playerId)"
}
/**
Senda a request to the server running the Aldo Framework.
- Parameters:
- uri: The request to be send.
- method: The HTTP method to be used for the request.
- parameters: The information that should be passed in the body
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
open class func request(uri: String, method: HTTPMethod, parameters: Parameters, callback: Callback? = nil) {
let headers = [
"Authorization": getAuthorizationHeaderValue()
]
Alamofire.request("\(hostAddress)\(uri)", method: method,
parameters: parameters, encoding: AldoEncoding(),
headers: headers).responseJSON { response in
var result: NSDictionary = [:]
if let JSON = response.result.value {
result = JSON as! NSDictionary
}
var responseCode: Int = 499
if let httpResponse = response.response {
responseCode = httpResponse.statusCode
}
AldoMainCallback(callback: callback).onResponse(request: uri,
responseCode: responseCode, response: result)
}
}
/**
Opens a websocket connection with the Aldo Framework.
- Parameters:
- path: The path to subscribe to
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
- Returns: An instance of *AldoWebSocket* representing the connection or
*nil* if the connection could not be made.
*/
public class func subscribe(path: String, callback: Callback) -> AldoWebSocket? {
if let url = URL(string: "ws://\(baseAddress)\(path)") {
let socket = AldoWebSocket(path: path, url: url, callback: callback)
socket.connect()
return socket
}
return nil
}
/**
Sends a request to obtain an authorization token.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestAuthToken(callback: Callback? = nil) {
let command: String = RequestURI.REQUEST_AUTH_TOKEN.rawValue
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to create a session.
- Parameters:
- username: The username to be used.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func createSession(username: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.SESSION_CREATE.rawValue, username)
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to join a session.
- Parameters:
- username: The username to be used.
- token: The token to join a session.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func joinSession(username: String, token: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.SESSION_JOIN.rawValue, token, username)
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve information about the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestSessionInfo(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_INFO.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve the players in the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestSessionPlayers(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_PLAYERS.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to change the status of the session.
- Parameters:
- newStatus: The new status of the session.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func changeSessionStatus(newStatus: Session.Status, callback: Callback? = nil) {
var command: String = RequestURI.SESSION_STATE_PLAY.rawValue
if newStatus == Session.Status.PAUSED {
command = RequestURI.SESSION_STATE_PAUSE.rawValue
}
request(uri: command, method: .put, parameters: [:], callback: callback)
}
/**
Sends a request to delete the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func deleteSession(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_DELETE.rawValue
request(uri: command, method: .delete, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve the players linked to the device.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestDevicePlayers(callback: Callback? = nil) {
let command: String = RequestURI.PLAYER_ALL.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve information about the player.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestPlayerInfo(callback: Callback? = nil) {
let command: String = RequestURI.PLAYER_INFO.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to change the username of the player.
- Parameters:
- username: The username to be used.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func updateUsername(username: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.PLAYER_USERNAME_UPDATE.rawValue, username)
request(uri: command, method: .put, parameters: [:], callback: callback)
}
}
|
5d6f2b2f8a11e079bded308d4f9d2aa3
| 35.206704 | 113 | 0.612251 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/Utility/WebProgressView.swift
|
gpl-2.0
|
2
|
import UIKit
import WebKit
import WordPressShared
/// A view to show progress when loading web pages.
///
/// Since UIWebView doesn't offer any real or estimate loading progress, this
/// shows an initial indication of progress and animates to a full bar when the
/// web view finishes loading.
///
class WebProgressView: UIProgressView {
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
@objc func startedLoading() {
alpha = Animation.visibleAlpha
progress = Progress.initial
}
@objc func finishedLoading() {
UIView.animate(withDuration: Animation.longDuration, animations: { [weak self] in
self?.progress = Progress.final
}, completion: { [weak self] _ in
UIView.animate(withDuration: Animation.shortDuration, animations: {
self?.alpha = Animation.hiddenAlhpa
})
})
}
func observeProgress(webView: WKWebView) {
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: [.new], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let webView = object as? WKWebView,
let keyPath = keyPath else {
return
}
switch keyPath {
case #keyPath(WKWebView.estimatedProgress):
progress = Float(webView.estimatedProgress)
isHidden = webView.estimatedProgress == 1
default:
assertionFailure("Observed change to web view that we are not handling")
}
}
private func configure() {
progressTintColor = .primary
backgroundColor = .listBackground
progressViewStyle = .bar
}
private enum Progress {
static let initial = Float(0.1)
static let final = Float(1.0)
}
private enum Animation {
static let shortDuration = 0.1
static let longDuration = 0.4
static let visibleAlpha = CGFloat(1.0)
static let hiddenAlhpa = CGFloat(0.0)
}
}
|
6879f9bf199bd3475eae46a0e20c60d3
| 29.931507 | 150 | 0.632861 | false | false | false | false |
breadwallet/breadwallet-ios
|
refs/heads/master
|
breadwallet/src/ViewControllers/TransactionsTableViewController.swift
|
mit
|
1
|
//
// TransactionsTableViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-16.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class TransactionsTableViewController: UITableViewController, Subscriber, Trackable {
// MARK: - Public
init(currency: Currency, wallet: Wallet?, didSelectTransaction: @escaping ([Transaction], Int) -> Void) {
self.wallet = wallet
self.currency = currency
self.didSelectTransaction = didSelectTransaction
self.showFiatAmounts = Store.state.showFiatAmounts
super.init(nibName: nil, bundle: nil)
}
deinit {
wallet?.unsubscribe(self)
Store.unsubscribe(self)
}
let didSelectTransaction: ([Transaction], Int) -> Void
var filters: [TransactionFilter] = [] {
didSet {
transactions = filters.reduce(allTransactions, { $0.filter($1) })
tableView.reloadData()
}
}
var didScrollToYOffset: ((CGFloat) -> Void)?
var didStopScrolling: (() -> Void)?
// MARK: - Private
var wallet: Wallet? {
didSet {
if wallet != nil {
subscribeToTransactionUpdates()
}
}
}
private let currency: Currency
private let transactionCellIdentifier = "TransactionCellIdentifier"
private var transactions: [Transaction] = []
private var allTransactions: [Transaction] = [] {
didSet { transactions = allTransactions }
}
private var showFiatAmounts: Bool {
didSet { reload() }
}
private var rate: Rate? {
didSet { reload() }
}
private let emptyMessage = UILabel.wrapping(font: .customBody(size: 16.0), color: .grayTextTint)
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TxListCell.self, forCellReuseIdentifier: transactionCellIdentifier)
tableView.separatorStyle = .none
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableView.automaticDimension
tableView.contentInsetAdjustmentBehavior = .never
let header = SyncingHeaderView(currency: currency)
header.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 40.0)
tableView.tableHeaderView = header
emptyMessage.textAlignment = .center
emptyMessage.text = S.TransactionDetails.emptyMessage
setupSubscriptions()
updateTransactions()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Store.trigger(name: .didViewTransactions(transactions))
}
private func setupSubscriptions() {
Store.subscribe(self,
selector: { $0.showFiatAmounts != $1.showFiatAmounts },
callback: { [weak self] state in
self?.showFiatAmounts = state.showFiatAmounts
})
Store.subscribe(self,
selector: { [weak self] oldState, newState in
guard let `self` = self else { return false }
return oldState[self.currency]?.currentRate != newState[self.currency]?.currentRate},
callback: { [weak self] state in
guard let `self` = self else { return }
self.rate = state[self.currency]?.currentRate
})
Store.subscribe(self, name: .txMetaDataUpdated("")) { [weak self] trigger in
guard let trigger = trigger else { return }
if case .txMetaDataUpdated(let txHash) = trigger {
_ = self?.reload(txHash: txHash)
}
}
subscribeToTransactionUpdates()
}
private func subscribeToTransactionUpdates() {
wallet?.subscribe(self) { [weak self] event in
guard let `self` = self else { return }
DispatchQueue.main.async {
switch event {
case .balanceUpdated, .transferAdded, .transferDeleted:
self.updateTransactions()
case .transferChanged(let transfer),
.transferSubmitted(let transfer, _):
if let txHash = transfer.hash?.description, self.reload(txHash: txHash) {
break
}
self.updateTransactions()
default:
break
}
}
}
wallet?.subscribeManager(self) { [weak self] event in
guard let `self` = self else { return }
DispatchQueue.main.async {
if case .blockUpdated = event {
self.updateTransactions()
}
}
}
}
// MARK: -
private func reload() {
assert(Thread.isMainThread)
tableView.reloadData()
if transactions.isEmpty {
if emptyMessage.superview == nil {
tableView.addSubview(emptyMessage)
emptyMessage.constrain([
emptyMessage.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
emptyMessage.topAnchor.constraint(equalTo: tableView.topAnchor, constant: E.isIPhone5 ? 50.0 : AccountHeaderView.headerViewMinHeight),
emptyMessage.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -C.padding[2]) ])
}
} else {
emptyMessage.removeFromSuperview()
}
}
private func reload(txHash: String) -> Bool {
assert(Thread.isMainThread)
guard let index = transactions.firstIndex(where: { txHash == $0.hash }) else { return false }
tableView.reload(row: index, section: 0)
return true
}
private func updateTransactions() {
assert(Thread.isMainThread)
if let transfers = wallet?.transfers {
allTransactions = transfers
reload()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transactions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return transactionCell(tableView: tableView, indexPath: indexPath)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelectTransaction(transactions, indexPath.row)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Cell Builders
extension TransactionsTableViewController {
private func transactionCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: transactionCellIdentifier,
for: indexPath) as? TxListCell
else { assertionFailure(); return UITableViewCell() }
let rate = self.rate ?? Rate.empty
let viewModel = TxListViewModel(tx: transactions[indexPath.row])
cell.setTransaction(viewModel,
showFiatAmounts: showFiatAmounts,
rate: rate,
isSyncing: currency.state?.syncState != .success)
return cell
}
}
extension TransactionsTableViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
didScrollToYOffset?(scrollView.contentOffset.y)
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
didStopScrolling?()
}
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
didStopScrolling?()
}
}
|
8445e3f8a0681a84e9cc86107cd32d1c
| 33.788793 | 154 | 0.596828 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/Utility/ObfuscationView.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCommonComponents
import UIKit
import WireSystem
final class ObfuscationView: UIImageView {
init(icon: StyleKitIcon) {
super.init(frame: .zero)
backgroundColor = .accentDimmedFlat
isOpaque = true
contentMode = .center
setIcon(icon, size: .tiny, color: UIColor.from(scheme: .background))
switch icon {
case .locationPin:
accessibilityLabel = "Obfuscated location message"
case .paperclip:
accessibilityLabel = "Obfuscated file message"
case .photo:
accessibilityLabel = "Obfuscated image message"
case .microphone:
accessibilityLabel = "Obfuscated audio message"
case .videoMessage:
accessibilityLabel = "Obfuscated video message"
case .link:
accessibilityLabel = "Obfuscated link message"
default:
accessibilityLabel = "Obfuscated view"
}
}
@available(*, unavailable)
required init(coder: NSCoder) {
fatal("initWithCoder: not implemented")
}
}
|
ca9c3b3e114c10ab515627b95d8088b1
| 32.277778 | 76 | 0.674457 | false | false | false | false |
sersoft-gmbh/XMLWrangler
|
refs/heads/master
|
Sources/XMLWrangler/XMLElement+Attributes.swift
|
apache-2.0
|
1
|
/// Describes a type that can turn itself into an `XMLElement.Attributes.Content`
public protocol XMLAttributeContentConvertible {
/// The attribute content of this type.
var xmlAttributeContent: XMLElement.Attributes.Content { get }
}
/// Describes a type that can be created from an `XMLElement.Attributes.Content` instance.
public protocol ExpressibleByXMLAttributeContent {
/// Creates a new instance of the conforming type using the given attribute content.
/// - Parameter xmlAttributeContent: The attribute content from which to create a new instance.
init?(xmlAttributeContent: XMLElement.Attributes.Content)
}
/// Describes a type that can be converted from and to an `XMLElement.Attributes.Content` instance.
public typealias XMLAttributeContentRepresentable = ExpressibleByXMLAttributeContent & XMLAttributeContentConvertible
extension String: XMLAttributeContentRepresentable {
/// inherited
@inlinable
public var xmlAttributeContent: XMLElement.Attributes.Content { .init(self) }
/// inherited
@inlinable
public init(xmlAttributeContent: XMLElement.Attributes.Content) {
self = xmlAttributeContent.rawValue
}
}
extension XMLAttributeContentConvertible where Self: RawRepresentable, RawValue == XMLElement.Attributes.Content.RawValue {
/// inherited
@inlinable
public var xmlAttributeContent: XMLElement.Attributes.Content { .init(rawValue) }
}
extension ExpressibleByXMLAttributeContent where Self: RawRepresentable, Self.RawValue: LosslessStringConvertible {
/// inherited
@inlinable
public init?(xmlAttributeContent: XMLElement.Attributes.Content) {
self.init(rawValueDescription: xmlAttributeContent.rawValue)
}
}
extension ExpressibleByXMLAttributeContent where Self: LosslessStringConvertible {
/// inherited
@inlinable
public init?(xmlAttributeContent: XMLElement.Attributes.Content) {
self.init(xmlAttributeContent.rawValue)
}
}
extension ExpressibleByXMLAttributeContent where Self: LosslessStringConvertible, Self: RawRepresentable, Self.RawValue: LosslessStringConvertible {
/// inherited
@inlinable
public init?(xmlAttributeContent: XMLElement.Attributes.Content) {
self.init(rawValueDescription: xmlAttributeContent.rawValue)
}
}
extension XMLElement {
/// Contains the attributes of an `XMLElement`.
@frozen
public struct Attributes: Equatable {
/// Represents the key of an attribute.
@frozen
public struct Key: RawRepresentable, Hashable, Codable, ExpressibleByStringLiteral, XMLAttributeContentRepresentable, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias RawValue = String
/// inherited
public typealias StringLiteralType = RawValue
/// inherited
public let rawValue: RawValue
/// inherited
public var description: String { rawValue }
/// inherited
public var debugDescription: String { "\(Self.self)(\(rawValue))" }
/// inherited
public init(rawValue: RawValue) { self.rawValue = rawValue }
/// Creates a new key using the given raw value.
@inlinable
public init(_ rawValue: RawValue) { self.init(rawValue: rawValue) }
/// inherited
@inlinable
public init(stringLiteral value: StringLiteralType) { self.init(rawValue: value) }
}
/// Represents the content of an attribute.
@frozen
public struct Content: RawRepresentable, Hashable, ExpressibleByStringLiteral, ExpressibleByStringInterpolation, XMLAttributeContentRepresentable, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias RawValue = String
/// inhertied
public typealias StringLiteralType = RawValue
/// inherited
public let rawValue: RawValue
/// inherited
@inlinable
public var description: String { rawValue }
/// inherited
public var debugDescription: String { "\(Self.self)(\(rawValue))" }
/// inherited
@inlinable
public var xmlAttributeContent: Content { self }
/// inherited
public init(rawValue: RawValue) { self.rawValue = rawValue }
/// Creates a new key using the given raw value.
@inlinable
public init(_ rawValue: RawValue) { self.init(rawValue: rawValue) }
/// inherited
@inlinable
public init(stringLiteral value: StringLiteralType) { self.init(rawValue: value) }
/// inherited
@inlinable
public init(xmlAttributeContent: Content) {
self = xmlAttributeContent
}
}
@usableFromInline
typealias Storage = Dictionary<Key, Content>
@usableFromInline
var storage: Storage
/// Returns the keys of in this `Attributes`.
@inlinable
public var keys: Keys { .init(storage: storage.keys) }
/// Returns the contents of in this `Attributes`. The `contents` can be mutated.
@inlinable
public var contents: Contents {
get { .init(storage: storage.values) }
set { storage.values = newValue.storage }
}
@usableFromInline
init(storage: Storage) {
self.storage = storage
}
/// Creates an empty attributes list.
@inlinable
public init() {
self.init(storage: .init())
}
/// Creates an empty attributes list that reserves the given capacity.
@inlinable
public init(minimumCapacity: Int) {
self.init(storage: .init(minimumCapacity: minimumCapacity))
}
/// Creates an attributes list with the given keys and contents.
/// - Parameter keysAndContents: The sequence of unique key and content tuples to initialize from.
/// - Precondition: The keys must be unique. Failure to fulfill this precondition will result in crahes.
@inlinable
public init<S>(uniqueKeysWithContents keysAndContents: S) where S: Sequence, S.Element == (Key, Content) {
self.init(storage: .init(uniqueKeysWithValues: keysAndContents))
}
/// Creates an attributes list with the given keys and contents, using a closure for uniquing keys.
/// - Parameters:
/// - keysAndContents: The sequence of key and content tuples to initialize from.
/// - combine: The closure to use for uniquing keys. The closure is passed the two contents for non-unique keys and should return the content to choose.
/// - Throws: Rethrows errors thrown by `combine`.
@inlinable
public init<S>(_ keysAndContents: S, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows
where S: Sequence, S.Element == (Key, Content)
{
try self.init(storage: .init(keysAndContents, uniquingKeysWith: combine))
}
/// Returns / sets the content for the given key.
/// When setting nil, the content is removed for the given key.
/// - Parameters key: The key to look up the content for.
/// - Returns: The content for the given key. `nil` if none is found.
@inlinable
public subscript(key: Key) -> Content? {
get { storage[key] }
set { storage[key] = newValue }
}
/// Returns / sets the content for the given key, using a default if the key does not exist.
/// - Parameters:
/// - key: The key to look up the content for.
/// - default: The default value to use if no value exists for the given `key`.
/// - Returns: The content for the given key. `default` if none is found.
@inlinable
public subscript<Default: XMLAttributeContentConvertible>(key: Key, default defaultValue: @autoclosure () -> Default) -> Content {
get { storage[key, default: defaultValue().xmlAttributeContent] }
set { storage[key, default: defaultValue().xmlAttributeContent] = newValue }
}
/// Filters the attributes using the given predicate closure.
/// - Parameter isIncluded: The closure to execute for each element.
/// Should return `true` for elements that should be in the resulting attributes.
/// - Throws: Any error thrown by `isIncluded`.
/// - Returns: The filtered attributes. Only elements for which `isIncluded` returned `true` are contained.
@inlinable
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Self {
try .init(storage: storage.filter(isIncluded))
}
/// Updates the content element for a given key.
/// - Parameters:
/// - content: The new content element to store for `key`.
/// - key: The key for which to update the content element.
/// - Returns: The old element of `key`, if there was one. `nil` otherwise.
@inlinable
@discardableResult
public mutating func updateContent(_ content: Content, forKey key: Key) -> Content? {
storage.updateValue(content, forKey: key)
}
/// Removes the content for a given key.
/// - Parameter key: The key for which to remove the content.
/// - Returns: The old values of `key`, if there was one. `nil` otherwise.
@inlinable
@discardableResult
public mutating func removeContent(forKey key: Key) -> Content? {
storage.removeValue(forKey: key)
}
/// Merges another sequence of key-content-pairs into the receiving attributes.
/// - Parameters:
/// - other: The sequence of key-content-pairs to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
@inlinable
public mutating func merge<S>(_ other: S, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows
where S: Sequence, S.Element == (Key, Content)
{
try storage.merge(other, uniquingKeysWith: combine)
}
/// Merges another attributes list into the receiving attributes.
/// - Parameters:
/// - other: The other attributes list to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
@inlinable
public mutating func merge(_ other: Self, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows {
try storage.merge(other.storage, uniquingKeysWith: combine)
}
/// Returns the result of merging another sequence of key-content-pairs with the receiving attributes.
/// - Parameters:
/// - other: The sequence of key-content-pairs to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
/// - Returns: The merged attributes list.
@inlinable
public func merging<S>(_ other: S, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows -> Self
where S: Sequence, S.Element == (Key, Content)
{
try .init(storage: storage.merging(other, uniquingKeysWith: combine))
}
/// Returns the result of merging another attributes list into the receiving attributes.
/// - Parameters:
/// - other: The other attributes list to merge.
/// - combine: The closure to use for uniquing keys. Called for each key-conflict with both contents.
/// The returned element is used, the other one discarded.
/// - Throws: Any error thrown by `combine`.
/// - Returns: The merged attributes list.
@inlinable
public func merging(_ other: Self, uniquingKeysWith combine: (Content, Content) throws -> Content) rethrows -> Self {
try .init(storage: storage.merging(other.storage, uniquingKeysWith: combine))
}
/// Removes all key-content pairs from the attributes.
/// Calling this method invalidates all indices of the attributes.
/// - Parameter keepCapacity: Whether the attributes should keep its underlying storage capacity. Defaults to `false`.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
storage.removeAll(keepingCapacity: keepCapacity)
}
}
}
extension Dictionary where Key == XMLElement.Attributes.Key, Value == XMLElement.Attributes.Content {
/// Initializes the dictionary using the storage of the given attributes.
/// - Parameter attributes: The `XMLElement.Attributes` whose contents should be contained in the dictionary.
@inlinable
public init(elementsOf attributes: XMLElement.Attributes) {
self = attributes.storage
}
}
extension XMLElement.Attributes: ExpressibleByDictionaryLiteral {
/// inherited
@inlinable
public init(dictionaryLiteral elements: (Key, XMLAttributeContentConvertible)...) {
self.init(storage: .init(uniqueKeysWithValues: elements.lazy.map { ($0, $1.xmlAttributeContent) }))
}
}
extension XMLElement.Attributes: Sequence {
/// inherited
public typealias Element = (key: Key, content: Content)
/// Casts the `Element` tuple to `Storage.Element`. Uses `unsafeBitCast` since the tuples only differ in labels.
@usableFromInline
static func _castElement(_ storageElement: Storage.Element) -> Element {
unsafeBitCast(storageElement, to: Element.self)
}
/// The iterator for iterating over attributes.
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
var storageIterator: Storage.Iterator
@usableFromInline
init(base: Storage.Iterator) {
storageIterator = base
}
/// inherited
@inlinable
public mutating func next() -> Element? {
storageIterator.next().map(_castElement)
}
}
/// inherited
@inlinable
public var underestimatedCount: Int { storage.underestimatedCount }
/// inherited
@inlinable
public func makeIterator() -> Iterator {
.init(base: storage.makeIterator())
}
}
extension XMLElement.Attributes: Collection {
/// The index for attributes.
@frozen
public struct Index: Comparable {
@usableFromInline
let storageIndex: Storage.Index
@usableFromInline
init(base: Storage.Index) {
storageIndex = base
}
/// inherited
@inlinable
public static func <(lhs: Self, rhs: Self) -> Bool {
lhs.storageIndex < rhs.storageIndex
}
}
/// inherited
@inlinable
public var isEmpty: Bool { storage.isEmpty }
/// inherited
@inlinable
public var count: Int { storage.count }
/// inherited
@inlinable
public var startIndex: Index {
.init(base: storage.startIndex)
}
/// inherited
@inlinable
public var endIndex: Index {
.init(base: storage.endIndex)
}
/// inherited
@inlinable
public func index(after i: Index) -> Index {
.init(base: storage.index(after: i.storageIndex))
}
/// inherited
@inlinable
public subscript(position: Index) -> Element {
Self._castElement(storage[position.storageIndex])
}
}
extension XMLElement.Attributes: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
"""
\(Self.self) [\(storage.count) key/content pair(s)] {
\(storage.map { " \($0.key): \($0.value)" }.joined(separator: "\n"))
}
"""
}
public var debugDescription: String {
"""
\(Self.self) [\(storage.count) key/content pair(s)] {
\(storage.map { " \($0.key): \($0.value.debugDescription)" }.joined(separator: "\n"))
}
"""
}
}
extension XMLElement.Attributes {
/// A collection of keys inside `XMLElement.Attributes`
@frozen
public struct Keys: Collection, Equatable, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias Element = XMLElement.Attributes.Key
/// inherited
public typealias Index = XMLElement.Attributes.Index
@usableFromInline
typealias Storage = XMLElement.Attributes.Storage.Keys
/// The iterator for iterating over `XMLElement.Attributes.Keys`.
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
var storageIterator: Storage.Iterator
@usableFromInline
init(base: Storage.Iterator) {
storageIterator = base
}
/// inherited
@inlinable
public mutating func next() -> Element? {
storageIterator.next()
}
}
@usableFromInline
let storage: Storage
/// inherited
public var description: String { Array(storage).description }
/// inherited
public var debugDescription: String { Array(storage).debugDescription }
@usableFromInline
init(storage: Storage) {
self.storage = storage
}
/// inherited
@inlinable
public var startIndex: Index {
.init(base: storage.startIndex)
}
/// inherited
@inlinable
public var endIndex: Index {
.init(base: storage.endIndex)
}
/// inherited
@inlinable
public subscript(position: Index) -> Element {
storage[position.storageIndex]
}
/// inherited
@inlinable
public func makeIterator() -> Iterator {
.init(base: storage.makeIterator())
}
/// inherited
@inlinable
public func index(after i: Index) -> Index {
.init(base: storage.index(after: i.storageIndex))
}
}
/// The (mutable) collection of contents for `XMLElement.Attributes`.
@frozen
public struct Contents: Collection, MutableCollection, CustomStringConvertible, CustomDebugStringConvertible {
/// inherited
public typealias Element = XMLElement.Attributes.Content
/// inherited
public typealias Index = XMLElement.Attributes.Index
@usableFromInline
typealias Storage = XMLElement.Attributes.Storage.Values
/// The iterator for iterating over `XMLElement.Attributes.Contents`.
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
var storageIterator: Storage.Iterator
@usableFromInline
init(base: Storage.Iterator) {
storageIterator = base
}
/// inherited
@inlinable
public mutating func next() -> Element? {
storageIterator.next()
}
}
@usableFromInline
var storage: Storage
/// inherited
public var description: String { Array(storage).description }
/// inherited
public var debugDescription: String { Array(storage).debugDescription }
@usableFromInline
init(storage: Storage) {
self.storage = storage
}
/// inherited
@inlinable
public var startIndex: Index {
.init(base: storage.startIndex)
}
/// inherited
@inlinable
public var endIndex: Index {
.init(base: storage.endIndex)
}
/// inherited
@inlinable
public subscript(position: Index) -> Element {
get { storage[position.storageIndex] }
set { storage[position.storageIndex] = newValue }
}
/// inherited
@inlinable
public func makeIterator() -> Iterator {
.init(base: storage.makeIterator())
}
/// inherited
@inlinable
public func index(after i: Index) -> Index {
.init(base: storage.index(after: i.storageIndex))
}
}
}
|
c5ef687d3c3257dd54179719300f157b
| 35.503497 | 210 | 0.624761 | false | false | false | false |
carsonmcdonald/PlaygroundExplorer
|
refs/heads/master
|
PlaygroundExplorer/BrowseTableViewController.swift
|
mit
|
1
|
import Cocoa
class BrowseTableViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var browseTableView : NSTableView!
private var playgroundDataFiles: [String] = []
private var playgroundRepoData: [String:[PlaygroundEntryRepoData]]?
override func viewDidAppear() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
StatusNotification.broadcastStatus("Updating metadata")
Utils.cloneOrUpdatePlaygroundData()
self.playgroundRepoData = Utils.getRepoInformationFromPlaygroundData()
self.loadAndParsePlaygroundData()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.browseTableView.reloadData()
StatusNotification.broadcastStatus("Metadata update complete")
})
})
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 75
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.makeViewWithIdentifier("BrowseTableCellView", owner: self) as? BrowseTableCellView {
if let playgroundData = self.parseJSONData(self.playgroundDataFiles[row]) {
cell.playgroundData = playgroundData
return cell
}
}
return nil
}
func tableViewSelectionDidChange(notification: NSNotification) {
if self.browseTableView.selectedRow >= 0 && self.playgroundDataFiles.count > self.browseTableView.selectedRow {
let playgroundDataFile = self.playgroundDataFiles[self.browseTableView.selectedRow]
if let playgroundData = self.parseJSONData(playgroundDataFile) {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.BrowsePlaygroundSelected, object: self, userInfo: ["playgroundData":playgroundData])
}
} else {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.BrowsePlaygroundSelected, object: self, userInfo: nil)
}
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return self.playgroundDataFiles.count
}
private func loadAndParsePlaygroundData() {
self.playgroundDataFiles.removeAll(keepCapacity: true)
let playgroundRepo = Utils.getPlaygroundRepoDirectory()
let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(playgroundRepo!, error: nil)
if files != nil {
for file in files! {
let filename = file as! String
if let range = filename.rangeOfString(".json") {
if range.endIndex == filename.endIndex {
if let jsonFile = playgroundRepo?.stringByAppendingPathComponent(filename) {
if NSFileManager.defaultManager().fileExistsAtPath(jsonFile) {
self.playgroundDataFiles.append(jsonFile)
}
}
}
}
}
}
}
private func parseJSONData(jsonFile:String) -> PlaygroundEntryData? {
if let jsonData = NSData(contentsOfFile: jsonFile) {
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments, error:&parseError)
if parseError != nil {
Utils.showErrorAlert("Error parsing json in \(jsonFile): \(parseError)")
} else {
if let playgroundDataDictionary = parsedObject as? NSDictionary {
if let playgroundData = PlaygroundEntryData(jsonData: playgroundDataDictionary) {
if self.playgroundRepoData != nil {
playgroundData.repoDataList = self.playgroundRepoData![jsonFile.lastPathComponent]
}
return playgroundData
} else {
Utils.showErrorAlert("Playground data format incorrect \(jsonFile)")
}
} else {
Utils.showErrorAlert("Root is not a dictionary \(jsonFile)")
}
}
} else {
Utils.showErrorAlert("Couldn't read file \(jsonFile)")
}
return nil
}
}
|
b95412019100950bbb79a65cab6bb07f
| 38.070866 | 178 | 0.566505 | false | false | false | false |
ludagoo/Perfect
|
refs/heads/master
|
PerfectLib/PerfectError.swift
|
agpl-3.0
|
2
|
//
// PerfectError.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/5/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
import LinuxBridge
var errno: Int32 {
return linux_errno()
}
#else
import Darwin
#endif
/// Some but not all of the exception types which may be thrown by the system
public enum PerfectError : ErrorType {
/// A network related error code and message.
case NetworkError(Int32, String)
/// A file system related error code and message.
case FileError(Int32, String)
/// A OS level error code and message.
case SystemError(Int32, String)
/// An API exception error message.
case APIError(String)
}
@noreturn
func ThrowFileError() throws {
let err = errno
let msg = String.fromCString(strerror(err))!
// print("FileError: \(err) \(msg)")
throw PerfectError.FileError(err, msg)
}
@noreturn
func ThrowSystemError() throws {
let err = errno
let msg = String.fromCString(strerror(err))!
// print("SystemError: \(err) \(msg)")
throw PerfectError.SystemError(err, msg)
}
@noreturn
func ThrowNetworkError() throws {
let err = errno
let msg = String.fromCString(strerror(err))!
// print("NetworkError: \(err) \(msg)")
throw PerfectError.NetworkError(err, msg)
}
|
d8df347b9a0de922b0ce0f7aabca8fd7
| 27.376623 | 92 | 0.735011 | false | false | false | false |
sdq/rrule.swift
|
refs/heads/master
|
rruledemo/rruledemo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// rruledemo
//
// Created by sdq on 7/20/16.
// Copyright © 2016 sdq. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var frequency: NSPopUpButton!
@IBOutlet weak var dtstart: NSDatePicker!
@IBOutlet weak var until: NSDatePicker!
@IBOutlet weak var count: NSTextField!
@IBOutlet weak var interval: NSTextField!
@IBOutlet weak var wkst: NSPopUpButton!
@IBOutlet weak var monday: NSButton!
@IBOutlet weak var tuesday: NSButton!
@IBOutlet weak var wednesday: NSButton!
@IBOutlet weak var thursday: NSButton!
@IBOutlet weak var friday: NSButton!
@IBOutlet weak var saturday: NSButton!
@IBOutlet weak var sunday: NSButton!
@IBOutlet weak var byweekno: NSTextField!
@IBOutlet weak var Jan: NSButton!
@IBOutlet weak var Feb: NSButton!
@IBOutlet weak var Mar: NSButton!
@IBOutlet weak var Apr: NSButton!
@IBOutlet weak var May: NSButton!
@IBOutlet weak var Jun: NSButton!
@IBOutlet weak var Jul: NSButton!
@IBOutlet weak var Aug: NSButton!
@IBOutlet weak var Sep: NSButton!
@IBOutlet weak var Oct: NSButton!
@IBOutlet weak var Nov: NSButton!
@IBOutlet weak var Dec: NSButton!
@IBOutlet weak var bymonthday: NSTextField!
@IBOutlet weak var byyearday: NSTextField!
@IBOutlet weak var bysetpos: NSTextField!
@IBOutlet weak var tableview: NSTableView!
var occurenceArray: [Date] = []
let frequencyArray = ["Yearly", "Monthly", "Weekly", "Daily"]
let weekdayArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
override func viewDidLoad() {
super.viewDidLoad()
tableview.dataSource = self
tableview.delegate = self
frequency.removeAllItems()
frequency.addItems(withTitles: frequencyArray)
wkst.removeAllItems()
wkst.addItems(withTitles: weekdayArray)
// frequency.indexOfSelectedItem
}
}
extension ViewController {
@IBAction func convert(_ sender: NSButton) {
//frequency
var rrulefrequency: RruleFrequency = .yearly
switch frequency.indexOfSelectedItem {
case 0:
rrulefrequency = .yearly
case 1:
rrulefrequency = .monthly
case 2:
rrulefrequency = .weekly
case 3:
rrulefrequency = .daily
default:
rrulefrequency = .yearly
}
//dtstart
let rruledtstart = dtstart.dateValue
//until
let rruleuntil = until.dateValue
//count
var rrulecount: Int?
if count.integerValue != 0 {
rrulecount = count.integerValue
}
//interval
var rruleinterval: Int = 1
if interval.integerValue != 0 {
rruleinterval = interval.integerValue
}
//wkst
let rrulewkst = wkst.indexOfSelectedItem
//byweekday
var rrulebyweekday: [Int] = []
if sunday.state.rawValue == 1 {
rrulebyweekday.append(1)
}
if monday.state.rawValue == 1 {
rrulebyweekday.append(2)
}
if tuesday.state.rawValue == 1 {
rrulebyweekday.append(3)
}
if wednesday.state.rawValue == 1 {
rrulebyweekday.append(4)
}
if thursday.state.rawValue == 1 {
rrulebyweekday.append(5)
}
if friday.state.rawValue == 1 {
rrulebyweekday.append(6)
}
if saturday.state.rawValue == 1 {
rrulebyweekday.append(7)
}
//byweekno
var rrulebyweekno: [Int] = []
let byweeknostring = byweekno.stringValue
let stringArray = byweeknostring.components(separatedBy: ",")
for x in stringArray {
if let y = Int(x) {
rrulebyweekno.append(y)
}
}
//bymonth
var rrulebymonth: [Int] = []
if Jan.state.rawValue == 1 {
rrulebymonth.append(1)
}
if Feb.state.rawValue == 1 {
rrulebymonth.append(2)
}
if Mar.state.rawValue == 1 {
rrulebymonth.append(3)
}
if Apr.state.rawValue == 1 {
rrulebymonth.append(4)
}
if May.state.rawValue == 1 {
rrulebymonth.append(5)
}
if Jun.state.rawValue == 1 {
rrulebymonth.append(6)
}
if Jul.state.rawValue == 1 {
rrulebymonth.append(7)
}
if Aug.state.rawValue == 1 {
rrulebymonth.append(8)
}
if Sep.state.rawValue == 1 {
rrulebymonth.append(9)
}
if Oct.state.rawValue == 1 {
rrulebymonth.append(10)
}
if Nov.state.rawValue == 1 {
rrulebymonth.append(11)
}
if Dec.state.rawValue == 1 {
rrulebymonth.append(12)
}
//bymonthday
var rrulebymonthday: [Int] = []
let bymonthdaystring = bymonthday.stringValue
let monthdayArray = bymonthdaystring.components(separatedBy: ",")
for x in monthdayArray {
if let y = Int(x) {
rrulebymonthday.append(y)
}
}
//byyearday
var rrulebyyearday: [Int] = []
let byyeardaystring = byyearday.stringValue
let byyeardayArray = byyeardaystring.components(separatedBy: ",")
for x in byyeardayArray {
if let y = Int(x) {
rrulebyyearday.append(y)
}
}
//bysetpos
var rrulebysetpos: [Int] = []
let bysetposstring = bysetpos.stringValue
let bysetposArray = bysetposstring.components(separatedBy: ",")
for x in bysetposArray {
if let y = Int(x) {
rrulebysetpos.append(y)
}
}
let rule = rrule(frequency: rrulefrequency, dtstart: rruledtstart, until: rruleuntil, count: rrulecount, interval: rruleinterval, wkst: rrulewkst, bysetpos: rrulebysetpos, bymonth: rrulebymonth, bymonthday: rrulebymonthday, byyearday: rrulebyyearday, byweekno: rrulebyweekno, byweekday: rrulebyweekday, byhour: [], byminute: [], bysecond: [])
occurenceArray = rule.getOccurrences()
tableview.reloadData()
}
}
extension ViewController: NSTableViewDataSource, NSTableViewDelegate {
func numberOfRows(in tableView: NSTableView) -> Int {
return occurenceArray.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cellView: NSTableCellView = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView
let item = occurenceArray[row]
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = TimeZone.current
let date = formatter.string(from: item)
cellView.textField!.stringValue = date
return cellView
}
}
|
2448f2d3b671f56f1546f9f189a968f4
| 30.740088 | 350 | 0.585149 | false | false | false | false |
cloudinary/cloudinary_ios
|
refs/heads/master
|
Cloudinary/Classes/ios/Uploader/CLDImagePreprocessChain.swift
|
mit
|
1
|
//
//
// CLDImagePreprocessChain.swift
//
// Copyright (c) 2017 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
/**
The CLDImagePreprocessChain is used to run preprocessing on images before uploading.
It support processing, validations and encoders, all fully customizable.
*/
public class CLDImagePreprocessChain: CLDPreprocessChain<UIImage> {
public override init() {
}
internal override func decodeResource(_ resourceData: Any) throws -> UIImage? {
if let url = resourceData as? URL {
if let resourceData = try? Data(contentsOf: url) {
return UIImage(data: resourceData)
}
} else if let data = resourceData as? Data {
return UIImage(data: data)
}
return nil
}
internal override func verifyEncoder() throws {
if (encoder == nil) {
setEncoder(CLDPreprocessHelpers.defaultImageEncoder)
}
}
}
|
9cec1b9643675a95c20a489545b614fa
| 36.925926 | 85 | 0.706543 | false | false | false | false |
AlexanderMazaletskiy/bodyweight-fitness-ios
|
refs/heads/master
|
FitForReddit/ContainerViewController.swift
|
mit
|
1
|
import UIKit
import QuartzCore
enum SlideOutState {
case BothCollapsed
case LeftPanelExpanded
case RightPanelExpanded
}
let centerPanelExpandedOffset: CGFloat = 60
class ContainerViewController: UIViewController {
var centerNavigationController: UINavigationController!
var centerViewController: CenterViewController!
var currentState: SlideOutState = SlideOutState.BothCollapsed {
didSet {
let shouldShowShadow = currentState != SlideOutState.BothCollapsed
showShadowForCenterViewController(shouldShowShadow)
}
}
var leftViewController: SidePanelViewController?
override func viewDidLoad() {
super.viewDidLoad()
centerViewController = UIStoryboard.centerViewController()
centerViewController.delegate = self
centerNavigationController = UINavigationController(rootViewController: centerViewController)
view.addSubview(centerNavigationController.view)
addChildViewController(centerNavigationController)
centerNavigationController.didMoveToParentViewController(self)
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:")
centerNavigationController.view.addGestureRecognizer(panGestureRecognizer)
}
}
extension ContainerViewController: CenterViewControllerDelegate {
func toggleLeftPanel() {
let notAlreadyExpanded = (currentState != .LeftPanelExpanded)
if notAlreadyExpanded {
addLeftPanelViewController()
}
animateLeftPanel(shouldExpand: notAlreadyExpanded)
}
func toggleRightPanel() {}
func addLeftPanelViewController() {
if leftViewController == nil {
leftViewController = UIStoryboard.leftViewController()
leftViewController!.animals = Animal.allCats()
addChildSidePanelController(leftViewController!)
}
}
func addChildSidePanelController(sidePanelController: SidePanelViewController) {
view.insertSubview(sidePanelController.view, atIndex: 0)
addChildViewController(sidePanelController)
sidePanelController.didMoveToParentViewController(self)
}
func addRightPanelViewController() {}
func animateLeftPanel(#shouldExpand: Bool) {
if (shouldExpand) {
currentState = .LeftPanelExpanded
animateCenterPanelXPosition(targetPosition: CGRectGetWidth(centerNavigationController.view.frame) - centerPanelExpandedOffset)
} else {
animateCenterPanelXPosition(targetPosition: 0) { finished in
self.currentState = .BothCollapsed
self.leftViewController!.view.removeFromSuperview()
self.leftViewController = nil;
}
}
}
func animateRightPanel(#shouldExpand: Bool) {}
func animateCenterPanelXPosition(#targetPosition: CGFloat, completion: ((Bool) -> Void)! = nil) {
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .CurveEaseInOut, animations: {
self.centerNavigationController.view.frame.origin.x = targetPosition
}, completion: completion)
}
func showShadowForCenterViewController(shouldShowShadow: Bool) {
if (shouldShowShadow) {
centerNavigationController.view.layer.shadowOpacity = 0.8
} else {
centerNavigationController.view.layer.shadowOpacity = 0.0
}
}
}
extension ContainerViewController: UIGestureRecognizerDelegate {
func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let gestureIsDraggingFromLeftToRight = (recognizer.velocityInView(view).x > 0)
switch(recognizer.state) {
case .Began:
if (currentState == .BothCollapsed) {
if (gestureIsDraggingFromLeftToRight) {
addLeftPanelViewController()
} else {
addRightPanelViewController()
}
showShadowForCenterViewController(true)
}
case .Changed:
recognizer.view!.center.x = recognizer.view!.center.x + recognizer.translationInView(view).x
recognizer.setTranslation(CGPointZero, inView: view)
case .Ended:
if(leftViewController != nil) {
// animate the side panel open or closed based on whether the view has moved more or less than halfway
let hasMovedGreaterThanHalfway = recognizer.view!.center.x > view.bounds.size.width
animateLeftPanel(shouldExpand: hasMovedGreaterThanHalfway)
}
default:
break
}
}
}
private extension UIStoryboard {
class func mainStoryboard() -> UIStoryboard {
return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
}
class func leftViewController() -> SidePanelViewController? {
return mainStoryboard().instantiateViewControllerWithIdentifier("LeftViewController") as? SidePanelViewController
}
class func centerViewController() -> CenterViewController? {
return mainStoryboard().instantiateViewControllerWithIdentifier("CenterViewController") as? CenterViewController
}
}
|
240614789489f975d7746fa873c38f3b
| 36.171233 | 144 | 0.672318 | false | false | false | false |
argent-os/argent-ios
|
refs/heads/master
|
app-ios/PasscodeSettingsViewController.swift
|
mit
|
1
|
//
// PasscodeSettingsViewController.swift
// PasscodeLockDemo
//
// Created by Yanko Dimitrov on 8/29/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
import PasscodeLock
class PasscodeSettingsViewController: UIViewController {
@IBOutlet weak var blueLabel: UILabel!
@IBOutlet weak var superView: UIView!
@IBOutlet weak var passcodeSwitch: UISwitch!
@IBOutlet weak var changePasscodeButton: UIButton!
@IBOutlet weak var backgroundView: UIView!
private let configuration: PasscodeLockConfigurationType
init(configuration: PasscodeLockConfigurationType) {
self.configuration = configuration
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
let repository = UserDefaultsPasscodeRepository()
configuration = PasscodeLockConfiguration(repository: repository)
super.init(coder: aDecoder)
}
// MARK: - View
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
view.backgroundColor = UIColor.whiteColor()
self.navigationController?.navigationBar.tintColor = UIColor.darkBlue()
updatePasscodeView()
}
override func viewDidLoad() {
passcodeSwitch.onTintColor = UIColor.oceanBlue()
backgroundView.backgroundColor = UIColor.offWhite()
self.navigationItem.title = "App Security"
self.navigationController?.navigationBar.titleTextAttributes = [
NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 17)!,
NSForegroundColorAttributeName: UIColor.darkBlue()
]
changePasscodeButton.layer.cornerRadius = 10
changePasscodeButton.clipsToBounds = true
changePasscodeButton.backgroundColor = UIColor(rgba: "#ffffff")
}
func updatePasscodeView() {
let hasPasscode = configuration.repository.hasPasscode
changePasscodeButton.hidden = !hasPasscode
passcodeSwitch.on = hasPasscode
}
// MARK: - Actions
@IBAction func passcodeSwitchValueChange(sender: AnyObject) {
let passcodeVC: PasscodeLockViewController
if passcodeSwitch.on {
passcodeVC = PasscodeLockViewController(state: .SetPasscode, configuration: configuration)
} else {
passcodeVC = PasscodeLockViewController(state: .RemovePasscode, configuration: configuration)
passcodeVC.successCallback = { lock in
self.passcodeSwitch.on = !self.passcodeSwitch.on
self.changePasscodeButton.hidden = true
lock.repository.deletePasscode()
}
}
presentViewController(passcodeVC, animated: true, completion: nil)
}
@IBAction func changePasscodeButtonTap(sender: AnyObject) {
let repo = UserDefaultsPasscodeRepository()
let config = PasscodeLockConfiguration(repository: repo)
let passcodeLock = PasscodeLockViewController(state: .ChangePasscode, configuration: config)
presentViewController(passcodeLock, animated: true, completion: nil)
}
//Changing Status Bar
override func prefersStatusBarHidden() -> Bool {
return false
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .Default
}
// This function is called before the segue, use this to make sure the view controller is properly returned to the root view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "homeView") {
let rootViewController = (self.storyboard?.instantiateViewControllerWithIdentifier("RootViewController"))! as UIViewController
self.presentViewController(rootViewController, animated: true, completion: nil)
}
}
}
|
09fda30c202ec6bc926a69330aab3c30
| 31.862903 | 139 | 0.658567 | false | true | false | false |
auth0/Lock.iOS-OSX
|
refs/heads/master
|
Lock/LoadingView.swift
|
mit
|
2
|
// LoadingView.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.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
class LoadingView: UIView, View {
weak var indicator: UIActivityIndicatorView?
var inProgress: Bool {
get {
return self.indicator?.isAnimating ?? false
}
set {
Queue.main.async {
if newValue {
self.indicator?.startAnimating()
} else {
self.indicator?.stopAnimating()
}
}
}
}
// MARK: - Initialisers
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = Style.Auth0.backgroundColor
#if swift(>=4.2)
let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
#else
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
#endif
apply(style: Style.Auth0)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(activityIndicator)
constraintEqual(anchor: activityIndicator.centerXAnchor, toAnchor: self.centerXAnchor)
constraintEqual(anchor: activityIndicator.centerYAnchor, toAnchor: self.centerYAnchor)
self.indicator = activityIndicator
self.indicator?.startAnimating()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func apply(style: Style) {
self.backgroundColor = style.backgroundColor
self.indicator?.color = style.disabledTextColor
}
}
|
5e7dcd97410132c59d3311ea23a7702c
| 35.534247 | 94 | 0.682415 | false | false | false | false |
wolfposd/DynamicFeedback
|
refs/heads/master
|
DynamicFeedbackSheets/DynamicFeedbackSheets/Controller/StartUpViewController.swift
|
gpl-2.0
|
1
|
//
// StartUpViewController.swift
// DynamicFeedbackSheets
//
// Created by Jan Hennings on 09/06/14.
// Copyright (c) 2014 Jan Hennings. All rights reserved.
//
import UIKit
class StartUpViewController: UIViewController, FeedbackSheetManagerDelegate, FeedbackSheetViewControllerDelegate {
// MARK: Properties
let manager = FeedbackSheetManager(baseURL: "http://beeqn.informatik.uni-hamburg.de/feedback/rest.php/")
let sheetID = "3"
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: IBActions
@IBAction func startFetch(sender: UIButton) {
manager.startFetchingSheetWithID("3")
}
// MARK: FeedbackSheetManagerDelegate
func feedbackSheetManager(manager: FeedbackSheetManager, didFinishFetchingSheet sheet: FeedbackSheet) {
performSegueWithIdentifier("presentFeedbackSheet", sender: sheet)
}
func feedbackSheetManager(manager: FeedbackSheetManager, didPostSheetWithSuccess success: Bool) {
println("Posting successful")
}
func feedbackSheetManager(manager: FeedbackSheetManager, didFailWithError error: NSError) {
println("Error (feedbackSheetManager didFailWithError) \(error)")
}
// MARK: FeedbackSheetViewControllerDelegate
func feedbackSheetViewController(controller: FeedbackSheetViewController, finishedWithResponse response: NSDictionary!) {
// next step: posting response
println("posting \(response)")
manager.postResponseWithSheetID(sheetID, response: response)
}
func feedbackSheetViewController(controller: FeedbackSheetViewController, didFailWithError error: NSError) {
// Error handling
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "presentFeedbackSheet" {
if let navigationController = segue.destinationViewController as? UINavigationController {
if let sheetViewController = navigationController.topViewController as? FeedbackSheetViewController {
sheetViewController.sheet = sender as FeedbackSheet
sheetViewController.delegate = self
}
}
}
}
}
|
93a16f508dd09b834a87f191c2bd9642
| 32.773333 | 125 | 0.684564 | false | false | false | false |
neoneye/SwiftyFORM
|
refs/heads/master
|
Example/Other/PickerViewViewController.swift
|
mit
|
1
|
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import SwiftyFORM
class PickerViewViewController: FormViewController {
override func populate(_ builder: FormBuilder) {
builder.navigationTitle = "PickerViews"
builder += SectionHeaderTitleFormItem().title("PickerView")
builder += picker0
builder += picker1
builder += picker2
builder += SectionHeaderTitleFormItem().title("Misc")
builder += summary
builder += randomizeButton
updateSummary()
}
lazy var picker0: PickerViewFormItem = {
let instance = PickerViewFormItem().title("1 component").behavior(.expanded)
instance.pickerTitles = [["0", "1", "2", "3", "4", "5", "6"]]
instance.valueDidChangeBlock = { [weak self] _ in
self?.updateSummary()
}
return instance
}()
lazy var picker1: PickerViewFormItem = {
let instance = PickerViewFormItem().title("2 components")
instance.pickerTitles = [["00", "01", "02", "03"], ["10", "11", "12", "13", "14"]]
instance.humanReadableValueSeparator = " :: "
instance.valueDidChangeBlock = { [weak self] _ in
self?.updateSummary()
}
return instance
}()
lazy var picker2: PickerViewFormItem = {
let instance = PickerViewFormItem().title("3 components")
instance.pickerTitles = [["00", "01", "02", "03"], ["10", "11", "12"], ["20", "21", "22", "23", "24"]]
instance.humanReadableValueSeparator = " % "
instance.valueDidChangeBlock = { [weak self] _ in
self?.updateSummary()
}
return instance
}()
lazy var summary: StaticTextFormItem = StaticTextFormItem().title("Values").value("-")
func updateSummary() {
let v0 = picker0.value
let v1 = picker1.value
let v2 = picker2.value
summary.value = "\(v0) , \(v1) , \(v2)"
}
lazy var randomizeButton: ButtonFormItem = {
let instance = ButtonFormItem()
instance.title = "Randomize"
instance.action = { [weak self] in
self?.randomize()
}
return instance
}()
func assignRandomValues(_ pickerView: PickerViewFormItem) {
var selectedRows = [Int]()
for rows in pickerView.pickerTitles {
if rows.count > 0 {
selectedRows.append(Int.random(in: 0..<rows.count))
} else {
selectedRows.append(-1)
}
}
pickerView.setValue(selectedRows, animated: true)
}
func randomize() {
assignRandomValues(picker0)
assignRandomValues(picker1)
assignRandomValues(picker2)
updateSummary()
}
}
|
35a280e95fd14e3956de90162295356a
| 27.349398 | 104 | 0.678708 | false | false | false | false |
bradhowes/SynthInC
|
refs/heads/master
|
SwiftMIDI/Performance.swift
|
mit
|
1
|
//
// Performance.swift
// SynthInC
//
// Created by Brad Howes on 6/6/16.
// Copyright © 2016 Brad Howes. All rights reserved.
//
import Foundation
import AVFoundation
public let phraseBeats = ScorePhrases.map { Int($0.duration * 4) }
public struct PerformerStats {
let remainingBeats: Int
let minPhrase: Int
let maxPhrase: Int
public var isDone: Bool { return remainingBeats == Int.max }
public init() {
self.init(remainingBeats: Int.max, minPhrase: Int.max, maxPhrase: Int.min)
}
public init(currentPhrase: Int) {
self.init(remainingBeats: Int.max, minPhrase: currentPhrase, maxPhrase: currentPhrase)
}
public init(remainingBeats: Int, currentPhrase: Int) {
self.init(remainingBeats: remainingBeats, minPhrase: currentPhrase, maxPhrase: currentPhrase)
}
public init(remainingBeats: Int, minPhrase: Int, maxPhrase: Int) {
self.remainingBeats = remainingBeats
self.minPhrase = minPhrase
self.maxPhrase = maxPhrase
}
public func merge(other: PerformerStats) -> PerformerStats {
return PerformerStats(remainingBeats: min(remainingBeats, other.remainingBeats),
minPhrase: min(minPhrase, other.minPhrase),
maxPhrase: max(maxPhrase, other.maxPhrase))
}
public func merge(other: Performer) -> PerformerStats {
return PerformerStats(remainingBeats: min(remainingBeats, other.remainingBeats),
minPhrase: min(minPhrase, other.currentPhrase),
maxPhrase: max(maxPhrase, other.currentPhrase))
}
}
public final class Performer {
private let index: Int
private let rando: Rando
public private(set) var currentPhrase = 0
public private(set) var remainingBeats: Int
public private(set) var played: Int = 0
public private(set) var desiredPlays: Int = 1
public private(set) var playCounts: [Int] = []
public private(set) var duration: MusicTimeStamp = 0.0
public init(index: Int, rando: Rando) {
self.index = index
self.rando = rando
self.remainingBeats = phraseBeats[0]
self.playCounts.reserveCapacity(ScorePhrases.count)
}
public func tick(elapsed: Int, minPhrase: Int, maxPhrase: Int) -> PerformerStats {
if currentPhrase == ScorePhrases.count {
return PerformerStats(currentPhrase: currentPhrase)
}
remainingBeats -= elapsed
if remainingBeats == 0 {
played += 1
let moveProb = currentPhrase == 0 ? 100 :
max(maxPhrase - currentPhrase, 0) * 15 - max(currentPhrase - minPhrase, 0) * 15 +
max(played - desiredPlays + 1, 0) * 100
if rando.passes(threshold: moveProb) {
playCounts.append(played)
duration += MusicTimeStamp(played) * ScorePhrases[currentPhrase].duration
currentPhrase += 1
if currentPhrase == ScorePhrases.count {
return PerformerStats(currentPhrase: currentPhrase)
}
played = 0
desiredPlays = rando.phraseRepetitions(phraseIndex: currentPhrase)
}
remainingBeats = phraseBeats[currentPhrase]
}
return PerformerStats(remainingBeats: remainingBeats, currentPhrase: currentPhrase)
}
public func finish(goal: MusicTimeStamp) {
precondition(playCounts.count == ScorePhrases.count)
guard let lastPhrase = ScorePhrases.last else { return }
while duration + lastPhrase.duration < goal {
playCounts[ScorePhrases.count - 1] += 1
duration += lastPhrase.duration
}
}
}
public protocol PerformanceGenerator {
func generate() -> [Part]
}
public final class BasicPerformanceGenerator : PerformanceGenerator {
var performers: [Performer]
public init(ensembleSize: Int, rando: Rando) {
performers = (0..<ensembleSize).map { Performer(index: $0, rando: rando) }
}
public func generate() -> [Part] {
var stats = performers.reduce(PerformerStats()) { $0.merge(other: $1) }
while !stats.isDone {
stats = performers.map({$0.tick(elapsed: stats.remainingBeats, minPhrase: stats.minPhrase, maxPhrase: stats.maxPhrase)})
.reduce(PerformerStats()) { $0.merge(other: $1) }
}
let goal = performers.compactMap({ $0.duration }).max() ?? 0.0
performers.forEach { $0.finish(goal: goal) }
return performers.map { $0.generatePart() }
}
}
public class Part {
public let index: Int
public let playCounts: [Int]
public let normalizedRunningDurations: [CGFloat]
public init(index: Int, playCounts: [Int], duration: MusicTimeStamp) {
self.index = index
self.playCounts = playCounts
let durations = zip(playCounts, ScorePhrases).map { MusicTimeStamp($0.0) * $0.1.duration }
let elapsed = durations.reduce(into: Array<MusicTimeStamp>()) {
$0.append(($0.last ?? ($0.reserveCapacity(playCounts.count), 0.0).1) + MusicTimeStamp($1))
}
normalizedRunningDurations = elapsed.map { CGFloat($0 / duration) }
}
public init?(data: Data) {
let decoder = NSKeyedUnarchiver(forReadingWith: data)
self.index = decoder.decodeInteger(forKey: "index")
guard let playCounts = decoder.decodeObject(forKey: "playCounts") as? [Int] else { return nil }
guard let normalizedRunningDurations = decoder.decodeObject(forKey: "normalizedRunningDurations") as? [CGFloat] else { return nil }
self.playCounts = playCounts
self.normalizedRunningDurations = normalizedRunningDurations
}
public func encodePerformance() -> Data {
let data = NSMutableData()
let encoder = NSKeyedArchiver(forWritingWith: data)
encoder.encode(index, forKey: "index")
encoder.encode(playCounts, forKey: "playCounts")
encoder.encode(normalizedRunningDurations, forKey: "normalizedRunningDurations")
encoder.finishEncoding()
return data as Data
}
public func timeline() -> String {
let scale = 1.0
return "\(index):" + playCounts.enumerated().map({"\($0.0)" + String(repeating: "-", count: Int(((MusicTimeStamp($0.1) * ScorePhrases[$0.0].duration) / scale).rounded(.up)))}).joined()
}
}
extension Performer {
func generatePart() -> Part {
return Part(index: index, playCounts: playCounts, duration: duration)
}
}
public class Performance {
public let parts: [Part]
public init(perfGen: PerformanceGenerator) {
self.parts = perfGen.generate()
}
public init?(data: Data) {
let decoder = NSKeyedUnarchiver(forReadingWith: data)
guard let configs = decoder.decodeObject(forKey: "parts") as? [Data] else { return nil }
let parts = configs.compactMap{ Part(data: $0) }
guard configs.count == parts.count else { return nil }
self.parts = parts
}
public func encodePerformance() -> Data {
let data = NSMutableData()
let encoder = NSKeyedArchiver(forWritingWith: data)
encoder.encode(parts.map { $0.encodePerformance() }, forKey: "parts")
encoder.finishEncoding()
return data as Data
}
public func playCounts() -> String {
return parts.map({$0.playCounts.map({String($0)}).joined(separator: " ")}).joined(separator: "\n")
}
public func timelines() -> String {
let lines = parts.map { $0.timeline() }
return lines.joined(separator: "\n")
}
}
|
aa77b7e49f5ccce2ddb891de980590cf
| 35.192488 | 192 | 0.631989 | false | false | false | false |
colemancda/NetworkObjects
|
refs/heads/develop
|
Source/Store.swift
|
mit
|
1
|
//
// Store.swift
// NetworkObjects
//
// Created by Alsey Coleman Miller on 9/14/15.
// Copyright © 2015 ColemanCDA. All rights reserved.
//
import SwiftFoundation
import CoreModel
public extension CoreModel.Store {
/// Caches the values of a response.
///
/// - Note: Request and Response must be of the same type or this method will do nothing.
func cacheResponse(response: Response, forRequest request: Request, dateCachedAttributeName: String?) throws {
switch (request, response) {
// 404 responses
case let (.Get(resource), .Error(errorStatusCode)):
// delete object from cache if not found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
case let (.Edit(resource, _), .Error(errorStatusCode)):
// delete object from cache if not found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
case let (.Delete(resource), .Error(errorStatusCode)):
// delete object from cache if now found response
if errorStatusCode == StatusCode.NotFound.rawValue {
if try self.exists(resource) {
try self.delete(resource)
}
}
// standard responses
case (.Get(let resource), .Get(var values)):
try self.createCachePlaceholders(values, entityName: resource.entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
// update values
if try self.exists(resource) {
try self.edit(resource, changes: values)
}
// create resource and set values
else {
try self.create(resource, initialValues: values)
}
case (let .Edit(resource, _), .Edit(var values)):
try self.createCachePlaceholders(values, entityName: resource.entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
// update values
if try self.exists(resource) {
try self.edit(resource, changes: values)
}
// create resource and set values
else {
try self.create(resource, initialValues: values)
}
case (let .Create(entityName, _), .Create(let resourceID, var values)):
try self.createCachePlaceholders(values, entityName: entityName)
// set cache date
if let dateCachedAttributeName = dateCachedAttributeName {
values[dateCachedAttributeName] = Value.Attribute(.Date(Date()))
}
let resource = Resource(entityName, resourceID)
try self.create(resource, initialValues: values)
case let (.Delete(resource), .Delete):
if try self.exists(resource) {
try self.delete(resource)
}
case let (.Search(fetchRequest), .Search(resourceIDs)):
for resourceID in resourceIDs {
let resource = Resource(fetchRequest.entityName, resourceID)
// create placeholder resources for results
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
}
default: break
}
}
}
private extension CoreModel.Store {
/// Resolves relationships in the values and creates placeholder resources.
private func createCachePlaceholders(values: ValuesObject, entityName: String) throws {
guard let entity = self.model[entityName] else { throw StoreError.InvalidEntity }
for (key, value) in values {
switch value {
case let .Relationship(relationshipValue):
guard let relationship = entity.relationships[key] else { throw StoreError.InvalidValues }
switch relationshipValue {
case let .ToOne(resourceID):
let resource = Resource(relationship.destinationEntityName, resourceID)
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
case let .ToMany(resourceIDs):
for resourceID in resourceIDs {
let resource = Resource(relationship.destinationEntityName, resourceID)
if try self.exists(resource) == false {
try self.create(resource, initialValues: ValuesObject())
}
}
}
default: break
}
}
}
}
|
0a0cb0e07c70a83de85330c7a3ffe28a
| 31.941799 | 114 | 0.473338 | false | false | false | false |
Dhvl-Golakiya/DGSnackbar
|
refs/heads/master
|
Pod/Classes/DGSnackbar.swift
|
mit
|
1
|
//
// DGSnackbar.swift
// DGSnackbar
//
// Created by Dhvl on 03/09/15.
// Copyright (c) 2015 Dhvl. All rights reserved.
//
import UIKit
@objc public class DGSnackbar: UIView {
public var backgroundView: UIView!
public var messageLabel: UILabel!
public var textInsets: UIEdgeInsets!
public var actionButton : UIButton!
public var interval = TimeInterval()
public var dismisTimer = Timer()
var actionBlock : ((DGSnackbar) -> Void)?
var dismissBlock : ((DGSnackbar) -> Void)?
let buttonWidth : CGFloat = 44
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
// 3. Setup view from .xib file
setAllViews()
}
func setAllViews() {
self.backgroundView = UIView()
self.backgroundView.frame = self.bounds
self.backgroundView.backgroundColor = UIColor(white: 0.1, alpha: 0.9)
self.backgroundView.layer.cornerRadius = 3
self.backgroundView.clipsToBounds = true
self.addSubview(self.backgroundView)
self.messageLabel = UILabel()
self.messageLabel.frame = self.bounds
self.messageLabel.textColor = UIColor.white
self.messageLabel.backgroundColor = UIColor.clear
self.messageLabel.font = UIFont.systemFont(ofSize: 14)
self.messageLabel.numberOfLines = 0
self.messageLabel.textAlignment = .center;
self.backgroundView.addSubview(self.messageLabel)
self.actionButton = UIButton()
self.actionButton.frame = self.bounds
self.actionButton.titleLabel?.textColor = UIColor.white
self.actionButton.backgroundColor = UIColor.clear
self.actionButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
self.actionButton.addTarget(self, action: #selector(onActionButtonPressed(button:)), for: UIControlEvents.touchUpInside)
self.backgroundView.addSubview(self.actionButton)
interval = 0
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceOrientationDidChange(sender:)),
name: NSNotification.Name.UIDeviceOrientationDidChange,
object: nil
)
}
@objc func deviceOrientationDidChange(sender: AnyObject?) {
updateView()
}
required convenience public init?(coder aDecoder: NSCoder) {
self.init()
}
func updateView() {
let deviceWidth = UIScreen.main.bounds.width
let constraintSize = CGSize(width: deviceWidth * (260.0 / 320.0), height: CGFloat.greatestFiniteMagnitude)
let textLabelSize = self.messageLabel.sizeThatFits(constraintSize)
self.messageLabel.frame = CGRect(
x: 5,
y: 5,
width: textLabelSize.width,
height: textLabelSize.height
)
self.backgroundView.frame = CGRect(
x: 2,
y: 0,
width: deviceWidth - 4,
height: self.messageLabel.frame.size.height + 10 >= 54 ? self.messageLabel.frame.size.height + 10 : 54
)
self.messageLabel.center = CGPoint(x: self.messageLabel.center.x, y: self.backgroundView.center.y)
self.actionButton.frame = CGRect(
x: deviceWidth - 51,
y: 5,
width: buttonWidth,
height: buttonWidth
)
self.setViewToBottom()
}
public func makeSnackbar(message : String?, actionButtonTitle : String?, interval : TimeInterval , actionButtonBlock : @escaping ((DGSnackbar) -> Void), dismisBlock : @escaping ((DGSnackbar) -> Void))-> (){
self.messageLabel.text = message
self.actionButton.setTitle(actionButtonTitle, for: UIControlState.normal)
self.interval = interval
self.actionBlock = actionButtonBlock
self.dismissBlock = dismisBlock
show()
}
public func makeSnackbar(message : String?, actionButtonImage : UIImage?, interval : TimeInterval , actionButtonBlock : @escaping ((DGSnackbar) -> Void), dismisBlock : @escaping ((DGSnackbar) -> Void))-> (){
let status = UserDefaults.standard.bool(forKey: "DGSnackbar")
if status {
self.dismissSnackBar()
}
self.messageLabel.text = message
self.actionButton.setImage(actionButtonImage, for: UIControlState.normal)
self.interval = interval
self.actionBlock = actionButtonBlock
self.dismissBlock = dismisBlock
show()
}
public func makeSnackbar(message : String?, interval : TimeInterval, dismisBlock : @escaping ((DGSnackbar) -> Void)) -> () {
self.messageLabel.text = message
self.actionButton.setTitle("", for: UIControlState.normal)
self.interval = interval
self.dismissBlock = dismisBlock
show()
}
func setViewToBottom() {
let screenSize = UIScreen.main.bounds.size
self.frame = CGRect(x: 0, y: screenSize.height , width: screenSize.width, height: self.backgroundView.frame.size.height);
}
func showView() {
let screenSize = UIScreen.main.bounds.size
self.frame = CGRect(x: 0, y: screenSize.height - self.backgroundView.frame.size.height - 2, width: screenSize.width, height: self.backgroundView.frame.size.height);
}
override public var window: UIWindow {
for window in UIApplication.shared.windows {
if NSStringFromClass(type(of: window)) == "UITextEffectsWindow" {
return window
}
}
return UIApplication.shared.windows.first!
}
func show() {
DispatchQueue.main.async {
self.updateView()
self.alpha = 0
self.window.addSubview(self)
UIView.animate(
withDuration: 0.2,
delay: 0,
options: UIViewAnimationOptions.curveEaseOut,
animations: {
self.showView()
self.alpha = 1
},
completion: nil)
self.dismisTimer = Timer.scheduledTimer(timeInterval: self.interval, target: self, selector: #selector(self.dismissSnackBar), userInfo: nil, repeats: false)
}
}
@objc func dismissSnackBar() {
self.dismisTimer.invalidate()
UIView.animate(
withDuration: 0.0,
delay: 0,
options: UIViewAnimationOptions.curveEaseIn,
animations: {
self.setViewToBottom()
self.alpha = 0
},
completion: { animation in
self.dismissBlock!(self)
self.removeFromSuperview()
})
}
@objc func onActionButtonPressed(button : UIButton!) {
self.actionBlock!(self)
dismissSnackBar()
}
}
|
106b8902c90f14910efeedb40141a69f
| 33.177885 | 211 | 0.599944 | false | false | false | false |
mozilla-mobile/focus-ios
|
refs/heads/main
|
Blockzilla/Pro Tips/ShareTrackersViewController.swift
|
mpl-2.0
|
1
|
/* 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 SnapKit
class ShareTrackersViewController: UIViewController {
private let trackerTitle: String
private let shareTap: (UIButton) -> Void
init(trackerTitle: String, shareTap: @escaping (UIButton) -> Void) {
self.trackerTitle = trackerTitle
self.shareTap = shareTap
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var trackerStatsLabel: UILabel = {
let trackerStatsLabel = UILabel()
trackerStatsLabel.font = .footnote14Light
trackerStatsLabel.textColor = .secondaryText
trackerStatsLabel.numberOfLines = 2
trackerStatsLabel.setContentHuggingPriority(.required, for: .horizontal)
trackerStatsLabel.setContentCompressionResistancePriority(.trackerStatsLabelContentCompressionPriority, for: .horizontal)
return trackerStatsLabel
}()
private lazy var shieldLogo: UIImageView = {
let shieldLogo = UIImageView()
shieldLogo.image = .trackingProtectionOn
shieldLogo.tintColor = UIColor.white
return shieldLogo
}()
private lazy var trackerStatsShareButton: UIButton = {
var button = UIButton()
button.setTitleColor(.secondaryText, for: .normal)
button.titleLabel?.font = .footnote14Light
button.titleLabel?.textAlignment = .center
button.setTitle(UIConstants.strings.share, for: .normal)
button.addTarget(self, action: #selector(shareTapped), for: .touchUpInside)
button.titleLabel?.numberOfLines = 0
button.layer.borderColor = UIColor.secondaryText.cgColor
button.layer.borderWidth = 1.0
button.layer.cornerRadius = 4
button.contentEdgeInsets = UIEdgeInsets(top: CGFloat.trackerStatsShareButtonTopBottomPadding, left: CGFloat.trackerStatsShareButtonLeadingTrailingPadding, bottom: CGFloat.trackerStatsShareButtonTopBottomPadding, right: CGFloat.trackerStatsShareButtonLeadingTrailingPadding)
button.setContentCompressionResistancePriority(.required, for: .horizontal)
button.setContentHuggingPriority(.required, for: .horizontal)
return button
}()
lazy var stackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [shieldLogo, trackerStatsLabel, trackerStatsShareButton])
stackView.spacing = .shareTrackerStackViewSpacing
stackView.alignment = .center
stackView.axis = .horizontal
return stackView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(stackView)
trackerStatsLabel.text = trackerTitle
shieldLogo.snp.makeConstraints {
$0.size.equalTo(CGFloat.shieldLogoSize)
}
stackView.snp.makeConstraints {
$0.center.equalToSuperview()
$0.leading.greaterThanOrEqualToSuperview().offset(CGFloat.shareTrackersLeadingTrailingOffset)
$0.trailing.lessThanOrEqualToSuperview().offset(CGFloat.shareTrackersLeadingTrailingOffset)
}
}
@objc private func shareTapped(sender: UIButton) {
shareTap(sender)
}
}
fileprivate extension CGFloat {
static let shieldLogoSize: CGFloat = 20
static let trackerStatsShareButtonTopBottomPadding: CGFloat = 10
static let trackerStatsShareButtonLeadingTrailingPadding: CGFloat = 8
static let shareTrackersLeadingTrailingOffset: CGFloat = 16
static let shareTrackerStackViewSpacing: CGFloat = 16
}
fileprivate extension UILayoutPriority {
static let trackerStatsLabelContentCompressionPriority = UILayoutPriority(999)
}
|
dda6f1f98d773b3349c35c298fa0291d
| 40.655914 | 281 | 0.720444 | false | false | false | false |
theeternalsw0rd/digital-signage-osx
|
refs/heads/master
|
Digital Signage/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Digital Signage
//
// Created by Micah Bucy on 12/17/15.
// Copyright © 2015 Micah Bucy. All rights reserved.
//
// The MIT License (MIT)
// This file is subject to the terms and conditions defined in LICENSE.md
import Cocoa
import AVKit
import AVFoundation
import CoreGraphics
struct jsonObject: Decodable {
let countdowns: [jsonCountdown]?
let items: [jsonSlideshowItem]
}
struct jsonCountdown: Decodable {
let day: Int
let hour: Int
let minute: Int
let duration: Int
}
struct jsonSlideshowItem: Decodable {
let type: String
let url: String
let md5sum: String
let filesize: Int
let duration: Int?
}
class ViewController: NSViewController {
private var url = NSURL(fileURLWithPath: "")
private var slideshow : [SlideshowItem] = []
private var slideshowLoader : [SlideshowItem] = []
private var countdowns : [Countdown] = []
private var slideshowLength = 0
private var currentSlideIndex = -1
private var timer = Timer()
private var updateTimer = Timer()
private var countdownTimer = Timer()
private var updateReady = false
private var initializing = true
private var animating = false
private var applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].path + "/theeternalsw0rd/Digital Signage"
private let appDelegate = NSApplication.shared.delegate as! AppDelegate
private let downloadQueue = OperationQueue()
private static var playerItemContext = 0
@IBOutlet weak var countdown: NSTextField!
@IBOutlet weak var goButton: NSButton!
@IBOutlet weak var addressBox: NSTextField!
@IBOutlet weak var label: NSTextField!
@IBAction func goButtonAction(_ sender: AnyObject) {
let urlString = self.addressBox.stringValue
UserDefaults.standard.set(urlString, forKey: "url")
self.loadSignage(urlString: urlString)
}
@IBAction func addressBoxAction(_ sender: AnyObject) {
let urlString = self.addressBox.stringValue
UserDefaults.standard.set(urlString, forKey: "url")
self.loadSignage(urlString: urlString)
}
func resetView() {
self.appDelegate.backgroundThread(background: {
while(self.animating) {
usleep(10000)
}
}, completion: {
self.stopSlideshow()
self.stopUpdater()
self.stopCountdowns()
self.countdown.isHidden = true
let urlString = UserDefaults.standard.string(forKey: "url")
self.initializing = true
self.releaseOtherViews(imageView: nil)
self.label.isHidden = false
self.addressBox.isHidden = false
if(urlString != nil) {
self.addressBox.stringValue = urlString!
}
self.addressBox.becomeFirstResponder()
self.goButton.isHidden = false
self.view.needsLayout = true
})
}
private func loadSignage(urlString: String) {
var isDir : ObjCBool = ObjCBool(false)
if(FileManager.default.fileExists(atPath: self.applicationSupport, isDirectory: &isDir)) {
if(!isDir.boolValue) {
let alert = NSAlert()
alert.messageText = "File already exists at caching directory path."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
return
}
}
else {
do {
try FileManager.default.createDirectory(atPath: self.applicationSupport, withIntermediateDirectories: true, attributes: nil)
}
catch let writeErr {
let alert = NSAlert()
alert.messageText = "Could not create caching directory. " + writeErr.localizedDescription
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
return
}
}
if let _url = URLComponents(string: urlString) {
var url = _url
url.scheme = "https"
if let urlString = url.url?.absoluteString {
if let _surl = NSURL(string: urlString) {
self.url = _surl
self.getJSON()
self.setCountdowns()
self.setUpdateTimer()
}
else {
let alert = NSAlert()
alert.messageText = "URL appears to be malformed."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
let alert = NSAlert()
alert.messageText = "URL appears to be malformed."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
let alert = NSAlert()
alert.messageText = "URL appears to be malformed."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
@objc func backgroundUpdate(timer:Timer) {
self.showNextSlide()
}
private func releaseOtherViews(imageView: NSView?) {
for view in self.view.subviews {
// hide views that need to retain properties
if(view != imageView && view != self.countdown && !(view.isHidden)) {
view.removeFromSuperview()
}
}
}
private func playVideo(frameSize: NSSize, boundsSize: NSSize, uri: NSURL) {
DispatchQueue.main.async(execute: { () -> Void in
let videoView = NSView()
videoView.frame.size = frameSize
videoView.bounds.size = boundsSize
videoView.wantsLayer = true
videoView.layerContentsRedrawPolicy = NSView.LayerContentsRedrawPolicy.onSetNeedsDisplay
let player = AVPlayer(url: uri as URL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resize
videoView.layer = playerLayer
videoView.layer?.backgroundColor = CGColor(red: 0, green: 0, blue: 0, alpha: 0)
self.view.addSubview(videoView, positioned: NSWindow.OrderingMode.below, relativeTo: self.countdown)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: player.currentItem)
player.currentItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &ViewController.playerItemContext)
player.play()
})
}
private func createImageView(image: NSImage, thumbnail: Bool, frameSize: NSSize, boundsSize: NSSize) {
DispatchQueue.main.async(execute: { () -> Void in
let imageView = MyImageView()
imageView.removeConstraints(imageView.constraints)
imageView.translatesAutoresizingMaskIntoConstraints = true
imageView.alphaValue = 0
if(thumbnail) {
imageView.image = image
}
else {
imageView.imageWithSize(image: image, w: frameSize.width, h: frameSize.height)
}
imageView.frame.size = frameSize
imageView.bounds.size = boundsSize
imageView.wantsLayer = true
imageView.layerContentsRedrawPolicy = NSView.LayerContentsRedrawPolicy.onSetNeedsDisplay
self.view.addSubview(imageView, positioned: NSWindow.OrderingMode.below, relativeTo: self.countdown)
self.animating = true
NSAnimationContext.runAnimationGroup(
{ (context) -> Void in
context.duration = 1.0
imageView.animator().alphaValue = 1.0
}, completionHandler: { () -> Void in
self.releaseOtherViews(imageView: imageView)
if(thumbnail) {
let item = self.slideshow[self.currentSlideIndex]
let path = item.path
let uri = NSURL(fileURLWithPath: path)
self.playVideo(frameSize: frameSize, boundsSize: boundsSize, uri: uri)
}
else {
self.setTimer()
}
self.animating = false
}
)
})
}
private func showNextSlide() {
DispatchQueue.main.async(execute: { () -> Void in
self.currentSlideIndex += 1
if(self.currentSlideIndex == self.slideshowLength) {
if(self.updateReady) {
self.updateSlideshow()
self.updateReady = false
return
}
self.currentSlideIndex = 0
}
if(self.slideshow.count == 0) {
if(self.updateReady) {
self.updateSlideshow()
self.updateReady = false
return
}
NSLog("Slideshow is empty at a point when it shouldn't be. Check server json response for properly configured data.")
self.setTimer()
return
}
let item = self.slideshow[self.currentSlideIndex]
let type = item.type
let path = item.path
let frameSize = self.view.frame.size
let boundsSize = self.view.bounds.size
if(type == "image") {
let image = NSImage(contentsOfFile: path)
self.createImageView(image: image!, thumbnail: false, frameSize: frameSize, boundsSize: boundsSize)
}
else if(type == "video") {
let uri = NSURL(fileURLWithPath: path)
let avAsset = AVURLAsset(url: uri as URL)
let avAssetImageGenerator = AVAssetImageGenerator(asset: avAsset)
let time = NSValue(time: CMTimeMake(0, 1))
avAssetImageGenerator.generateCGImagesAsynchronously(forTimes: [time],
completionHandler: {(_, image:CGImage?, _, _, error:Error?) in
if(error == nil) {
self.createImageView(image: NSImage(cgImage: image!, size: frameSize), thumbnail: true, frameSize: frameSize, boundsSize: boundsSize)
}
else {
self.playVideo(frameSize: frameSize, boundsSize: boundsSize, uri: uri)
}
}
)
}
else {
self.setTimer()
}
})
}
@objc func playerDidFinishPlaying(note: NSNotification) {
self.showNextSlide()
NotificationCenter.default.removeObserver(self)
}
private func stopSlideshow() {
DispatchQueue.main.async(execute: {
self.timer.invalidate()
})
}
private func stopUpdater() {
DispatchQueue.main.async(execute: {
self.updateTimer.invalidate()
})
}
private func stopCountdowns() {
DispatchQueue.main.async(execute: {
self.countdownTimer.invalidate()
})
}
private func setCountdowns() {
DispatchQueue.main.async(execute: {
self.countdownTimer.invalidate()
self.countdownTimer = Timer(timeInterval: 0.1, target: self, selector: #selector(self.updateCountdowns), userInfo: nil, repeats: true)
RunLoop.current.add(self.countdownTimer, forMode: RunLoopMode.commonModes)
})
}
private func setUpdateTimer() {
DispatchQueue.main.async(execute: {
self.updateTimer.invalidate()
self.updateTimer = Timer(timeInterval: 30, target: self, selector: #selector(self.update), userInfo: nil, repeats: false)
RunLoop.current.add(self.updateTimer, forMode: RunLoopMode.commonModes)
})
}
private func setTimer() {
DispatchQueue.main.async(execute: {
var duration: Double = 7.0
if(self.slideshow.count > 0) {
let item = self.slideshow[self.currentSlideIndex]
duration = Double(item.duration)
}
self.timer = Timer(timeInterval: duration, target: self, selector: #selector(self.backgroundUpdate), userInfo: nil, repeats: false)
RunLoop.current.add(self.timer, forMode: RunLoopMode.commonModes)
})
}
private func startSlideshow() {
self.showNextSlide()
}
private func downloadItems() {
if(self.downloadQueue.operationCount > 0) {
return
}
self.downloadQueue.isSuspended = true
for item in self.slideshowLoader {
if(FileManager.default.fileExists(atPath: item.path)) {
if(item.status == 1) {
continue
}
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: item.path)
} catch {
NSLog("Could not remove existing file: %@", item.path)
continue
}
let operation = Downloader(item: item)
self.downloadQueue.addOperation(operation)
}
else {
let operation = Downloader(item: item)
self.downloadQueue.addOperation(operation)
}
}
self.appDelegate.backgroundThread(background: {
self.downloadQueue.isSuspended = false
while(self.downloadQueue.operationCount > 0) {
usleep(100000)
}
}, completion: {
if(self.initializing) {
self.initializing = false
self.goButton.isHidden = true
self.addressBox.resignFirstResponder()
self.addressBox.isHidden = true
self.label.isHidden = true
self.view.becomeFirstResponder()
// move cursor works around mac mini 10.13 bug
var cursorPoint = CGPoint(x: 500, y: 500)
if let screen = NSScreen.main {
// work around cursor sometimes getting stuck in visible state
cursorPoint = CGPoint(x: screen.frame.width, y: screen.frame.height)
}
CGWarpMouseCursorPosition(cursorPoint)
if(!(self.view.window?.styleMask)!.contains(NSWindow.StyleMask.fullScreen)) {
self.view.window?.toggleFullScreen(nil)
}
/* should use this but breaks things on mac minis 10.13 and higher
if(!(self.view.isInFullScreenMode)) {
let presOptions: NSApplicationPresentationOptions =
[NSApplicationPresentationOptions.hideDock, NSApplicationPresentationOptions.hideMenuBar, NSApplicationPresentationOptions.disableAppleMenu]
let optionsDictionary = [NSFullScreenModeApplicationPresentationOptions :
presOptions]
self.view.enterFullScreenMode(NSScreen.main()!, withOptions:optionsDictionary)
}
*/
let view = self.view as! MyView
view.trackMouse = true
view.hideCursor()
view.setTimeout()
self.updateSlideshow()
}
else {
self.updateReady = true
}
})
}
private func updateSlideshow() {
self.stopSlideshow()
self.slideshow = self.slideshowLoader
self.slideshowLength = self.slideshow.count
self.currentSlideIndex = -1
self.slideshowLoader = []
self.appDelegate.backgroundThread(
background: {
let items = self.slideshow
do {
let files = try FileManager.default.contentsOfDirectory(atPath: self.applicationSupport)
for file in files {
let filePath = self.applicationSupport + "/" + file
var remove = true
for item in items {
if(file == "json.txt" || item.path == filePath) {
remove = false
break
}
}
if(remove) {
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: filePath)
} catch {
NSLog("Could not remove existing file: %@", filePath)
continue
}
}
}
} catch let readErr {
NSLog("Could not read files from caching directory. " + readErr.localizedDescription)
}
}, completion: {
self.setUpdateTimer()
}
)
self.startSlideshow()
}
func getDayOfWeek(date: NSDate)->Int? {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let myComponents = myCalendar?.components(NSCalendar.Unit.weekday, from: date as Date)
let weekDay = myComponents?.weekday
return weekDay
}
@objc func updateCountdowns() {
let date = NSDate()
let currentDay = getDayOfWeek(date: date)
let calendar = NSCalendar.current
let components = calendar.dateComponents([.hour, .minute, .second], from: date as Date)
let hour = components.hour ?? 0
let minute = components.minute ?? 0
let second = components.second ?? 0
let seconds = hour * 3600 + minute * 60 + second
var hide = true
for countdown in self.countdowns {
if(countdown.day != currentDay || countdown.duration > countdown.minute + countdown.hour * 60) {
continue
}
let countdownSeconds = countdown.hour * 3600 + countdown.minute * 60
let difference = countdownSeconds - seconds
if(difference > 0 && difference <= countdown.duration * 60) {
var minuteString = ""
var secondString = ""
hide = false
let minuteDifference = Int(difference / 60)
let secondDifference = difference % 60
if(minuteDifference < 10) {
minuteString = "0" + String(minuteDifference)
}
else {
minuteString = String(minuteDifference)
}
if(secondDifference < 10) {
secondString = "0" + String(secondDifference)
}
else {
secondString = String(secondDifference)
}
self.countdown.stringValue = minuteString + ":" + secondString
break
}
}
self.countdown.isHidden = hide
}
@objc func update() {
self.getJSON()
}
private func generateCountdowns(countdowns: [jsonCountdown]?) {
self.countdowns = []
guard let countdowns = countdowns
else { return }
for countdown in countdowns {
let day = countdown.day
let hour = countdown.hour
let minute = countdown.minute
let duration = countdown.duration
let newCountdown = Countdown(day: day, hour: hour, minute: minute, duration: duration)
self.countdowns.append(newCountdown)
}
}
private func getJSON() {
if(self.updateReady) {
// don't update while previous update in queue
self.setUpdateTimer()
return
}
let jsonLocation = self.applicationSupport + "/json.txt"
let userAgent = "Digital Signage"
let request = NSMutableURLRequest(url: self.url as URL)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
let session = URLSession.shared
let _ = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if error == nil {
if let dumpData = data {
let dumpNSData = NSData(data: dumpData)
do {
var cachedJSON = try JSONDecoder().decode(jsonObject.self, from: dumpData)
if let cachedData = NSData(contentsOfFile: String(describing: jsonLocation)) {
do {
let localCachedJSON = try JSONDecoder().decode(jsonObject.self, from: cachedData as Data)
cachedJSON = localCachedJSON
if(dumpNSData.isEqual(to: cachedData) && !self.initializing) {
self.setUpdateTimer()
NSLog("No changes")
return
}
if (!(dumpNSData.write(toFile: jsonLocation, atomically: true))) {
NSLog("Unable to write to file %@", jsonLocation)
}
} catch let jsonErr {
NSLog("Catch 1: Could not parse json from data. " + jsonErr.localizedDescription)
}
}
else {
if (!(dumpNSData.write(toFile: jsonLocation, atomically: true))) {
NSLog("Unable to write to file %@", jsonLocation)
}
}
do {
let json = try JSONDecoder().decode(jsonObject.self, from: dumpData)
self.generateCountdowns(countdowns: json.countdowns)
let items = json.items
let cachedItems = cachedJSON.items
if(items.count > 0) {
self.slideshowLoader.removeAll()
for item in items {
let itemUrl = item.url
if let itemNSURL = NSURL(string: itemUrl) {
let type = item.type
if let filename = itemNSURL.lastPathComponent {
let cachePath = self.applicationSupport + "/" + filename
let slideshowItem = SlideshowItem(url: itemNSURL as URL, type: type, path: cachePath)
if(type == "image") {
if let duration = item.duration {
slideshowItem.duration = duration
}
}
do {
let fileAttributes : NSDictionary? = try FileManager.default.attributesOfItem(atPath: NSURL(fileURLWithPath: cachePath, isDirectory: false).path!) as NSDictionary?
if let fileSizeNumber = fileAttributes?.fileSize() {
let fileSize = fileSizeNumber
for cachedItem in cachedItems {
if(itemUrl == cachedItem.url) {
if(item.md5sum == cachedItem.md5sum && item.filesize == fileSize) {
slideshowItem.status = 1
}
}
}
}
}
catch {
}
self.slideshowLoader.append(slideshowItem)
}
else {
NSLog("Could not retrieve filename from url: %@", itemUrl)
}
}
else {
continue
}
}
self.downloadItems()
}
} catch let jsonErr {
NSLog("Catch 3: Could not parse json from data. " + jsonErr.localizedDescription)
return
}
} catch let jsonErr {
NSLog("Catch 2: Could not parse json from data. " + jsonErr.localizedDescription)
return
}
}
else {
let alert = NSAlert()
alert.messageText = "Couldn't process data."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
if(self.initializing) {
if let cachedData = NSData(contentsOfFile: String(describing: jsonLocation)) {
do {
let json = try JSONDecoder().decode(jsonObject.self, from: cachedData as Data)
self.generateCountdowns(countdowns: json.countdowns)
let items = json.items
if(items.count > 0) {
for item in items {
let itemUrl = item.url
if let itemNSURL = NSURL(string: itemUrl) {
let type = item.type
if let filename = itemNSURL.lastPathComponent {
let cachePath = self.applicationSupport + "/" + filename
if(FileManager.default.fileExists(atPath: cachePath)) {
let slideshowItem = SlideshowItem(url: itemNSURL as URL, type: type, path: cachePath)
slideshowItem.status = 1
self.slideshowLoader.append(slideshowItem)
}
}
else {
NSLog("Could not retrieve filename from url: %@", itemUrl)
}
}
else {
continue
}
}
self.downloadItems()
}
} catch let jsonErr {
let alert = NSAlert()
alert.messageText = "Could not parse json from data. " + jsonErr.localizedDescription
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
let alert = NSAlert()
alert.messageText = "Couldn't load data."
alert.addButton(withTitle: "OK")
let _ = alert.runModal()
}
}
else {
NSLog("Offline")
self.setUpdateTimer()
}
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.window?.acceptsMouseMovedEvents = true
self.countdown.isHidden = true
self.countdown.alphaValue = 0.7
}
override func viewDidAppear() {
super.viewDidAppear()
if let urlString = UserDefaults.standard.string(forKey: "url") {
self.loadSignage(urlString: urlString)
}
if(self.addressBox.isDescendant(of: self.view)) {
DispatchQueue.main.async(execute: { () -> Void in
self.addressBox.becomeFirstResponder()
})
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if(context == &ViewController.playerItemContext) {
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .readyToPlay:
break
case .failed:
(object as! AVPlayerItem?)?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &ViewController.playerItemContext)
self.showNextSlide()
break
case .unknown:
(object as! AVPlayerItem?)?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &ViewController.playerItemContext)
self.showNextSlide()
break
}
}
}
else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
|
3c0216665fae42712798266562f188b3
| 42.833568 | 211 | 0.495238 | false | false | false | false |
shial4/VaporGCM
|
refs/heads/master
|
Sources/VaporGCM/GCMPayload.swift
|
mit
|
1
|
//
// GCMPayload.swift
// VaporGCM
//
// Created by Shial on 11/04/2017.
//
//
import Foundation
import JSON
///Parameters for gcmPayload messaging by platform
public struct GCMPayload {
// Simple, empty initializer
public init() {}
//Indicates notification title. This field is not visible on iOS phones and tablets.
public var title: String?
//Indicates notification body text.
public var body: String?
//Indicates notification icon.
public var icon: String = "myicon"
//Indicates a sound to play when the device receives the notification.
public var sound: String?
///Indicates whether each notification message results in a new entry on the notification center. If not set, each request creates a new notification. If set, and a notification with the same tag is already being shown, the new notification replaces the existing one in notification center.
public var tag: String?
///Indicates color of the icon, expressed in #rrggbb format
public var color: String?
///The action associated with a user click on the notification.
public var clickAction: String?
///Indicates the key to the body string for localization.
public var bodyLocKey: String?
///Indicates the string value to replace format specifiers in body string for localization.
public var bodyLocArgs: JSON?
///Indicates the key to the title string for localization.
public var titleLocKey: JSON?
///Indicates the string value to replace format specifiers in title string for localization.
public var titleLocArgs: JSON?
public func makeJSON() throws -> JSON {
var payload: [String: NodeRepresentable] = ["icon":icon]
if let value = title {
payload["title"] = value
}
if let value = body {
payload["body"] = value
}
if let value = sound {
payload["sound"] = value
}
if let value = tag {
payload["tag"] = value
}
if let value = color {
payload["color"] = value
}
if let value = clickAction {
payload["click_action"] = value
}
if let value = bodyLocKey {
payload["body_loc_key"] = value
}
if let value = bodyLocArgs {
payload["body_loc_args"] = value
}
if let value = titleLocKey {
payload["title_loc_key"] = value
}
if let value = titleLocArgs {
payload["title_loc_args"] = value
}
let json = JSON(node: try payload.makeNode(in: nil))
return json
}
}
public extension GCMPayload {
public init(message: String) {
self.init()
self.body = message
}
public init(title: String, body: String) {
self.init()
self.title = title
self.body = body
}
}
|
89199caa3e0692821f330efef4d2b05c
| 32.195402 | 294 | 0.621537 | false | false | false | false |
randymarsh77/amethyst
|
refs/heads/master
|
players/iOS/Sources/AppViewModel.swift
|
mit
|
1
|
import AVFoundation
import Foundation
import Async
import Bonjour
import Cancellation
import Crystal
import Fetch
import Scope
import Sockets
import Streams
import Time
import Using
import WKInterop
public class AppModel
{
public init(_ interop: WKInterop) {
_interop = interop
_state = State()
_state.statusMessage = "Idle"
_visualizer = VisualizerViewModel(interop)
_player = V2AudioStreamPlayer()
_ = _interop.registerEventHandler(route: "js.togglePlayPause") {
self.togglePlayPause()
}
_ = _interop.registerEventHandler(route: "js.ready") {
self.publishState()
}
_ = _interop.registerRequestHandler(route: "cover") {
return GetCover()
}
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayback)
try! session.setActive(true)
tryConnect()
}
private func tryConnect() {
let qSettings = QuerySettings(
serviceType: .Unregistered(identifier: "_crystal-content"),
serviceProtocol: .TCP,
domain: .AnyDomain
)
self.setStatusMessage("Searching for services...")
DispatchQueue.global(qos: .default).async
{
let service = await (Bonjour.FindAll(qSettings)).first
if (service != nil)
{
self.setStatusMessage("Found service, attempting to resolve host...")
await (Bonjour.Resolve(service!))
let endpoint = service!.getEndpointAddress()!
self.setStatusMessage("Resolved host to \(endpoint.host) on port \(endpoint.port)")
let client = TCPClient(endpoint: endpoint)
using ((try! client.tryConnect())!) { (socket: Socket) in
using (socket.createAudioStream()) { (audio: ReadableStream<AudioData>) in
self.setIsPlaying(true)
socket.pong()
_ = audio
.pipe(to: self._player.stream)
// .convert(to: kAudioFormatLinearPCM)
// .pipe(to: self._visualizer.stream)
await (Cancellation(self._playTokenSource!.token))
}}
}
else
{
self.setStatusMessage("No services found :(")
}
}
}
private func togglePlayPause() {
DispatchQueue.main.async {
NSLog("Toggling play state")
if (self._state.isPlaying) {
self.setIsPlaying(false)
} else {
self.tryConnect()
}
}
}
private func setStatusMessage(_ message: String) {
DispatchQueue.main.async {
NSLog("Setting status: %@", message)
self._state.statusMessage = message
self.publishState()
}
}
private func setIsPlaying(_ playing: Bool) {
if (self._state.isPlaying == playing) {
return
}
_playTokenSource?.cancel()
_playTokenSource = CancellationTokenSource()
self._state.isPlaying = playing
DispatchQueue.main.async {
self.publishState()
}
}
private func publishState() {
_interop.publish(route: "swift.set.state", content: _state)
}
private var _interop: WKInterop
private var _state: State
private var _visualizer: VisualizerViewModel
private var _player: V2AudioStreamPlayer
private var _playTokenSource: CancellationTokenSource?
}
func GetCover() -> Task<String>
{
return async { (task: Task<String>) in
let qSettings = QuerySettings(
serviceType: .Unregistered(identifier: "_crystal-meta"),
serviceProtocol: .TCP,
domain: .AnyDomain
)
var result = ""
DispatchQueue.global(qos: .default).async
{
let service = await (Bonjour.FindAll(qSettings)).first
if (service != nil)
{
await (Bonjour.Resolve(service!))
let endpoint = service!.getEndpointAddress()!
let url = "http://\(endpoint.host):\(endpoint.port)/art"
let data = await (Fetch(URL(string: url)!))
if (data != nil) {
result = "data:image/png;base64,\(data!.base64EncodedString())"
}
}
Async.Wake(task)
}
Async.Suspend()
return result
}
}
fileprivate func Cancellation(_ token: CancellationToken) -> Task<Void> {
let task = async {
Async.Suspend()
}
_ = try! token.register {
Async.Wake(task)
}
return task
}
|
1cd3cf4af2f765f4476abf5b112f96c2
| 21.869822 | 87 | 0.687451 | false | false | false | false |
fromkk/Valy
|
refs/heads/master
|
Sources/ValyHelper.swift
|
mit
|
1
|
//
// ValyHelper.swift
// Validator
//
// Created by Kazuya Ueoka on 2016/11/15.
//
//
import Foundation
@objc public enum ValidatorRule: Int {
case required
case match
case pattern
case alphabet
case digit
case alnum
case number
case minLength
case maxLength
case exactLength
case numericMin
case numericMax
case numericBetween
}
@objc public class Validator: NSObject {
private let shared: AnyValidator = Valy.factory()
@objc(addRule:)
public func add(rule: ValidatorRule) -> Self {
return self.add(rule: rule, value1: nil, value2: nil)
}
@objc(addRule:value:)
public func add(rule: ValidatorRule, value: Any?) -> Self {
return self.add(rule: rule, value1: value, value2: nil)
}
@objc(addRule:value1:value2:)
public func add(rule: ValidatorRule, value1: Any?, value2: Any?) -> Self {
switch rule {
case .required:
self.shared.add(rule: ValyRule.required)
case .match:
guard let match: String = value1 as? String else {
return self
}
self.shared.add(rule: ValyRule.match(match))
case .pattern:
guard let pattern: String = value1 as? String else {
return self
}
self.shared.add(rule: ValyRule.pattern(pattern))
case .alphabet:
self.shared.add(rule: ValyRule.alphabet)
case .digit:
self.shared.add(rule: ValyRule.digit)
case .alnum:
self.shared.add(rule: ValyRule.alnum)
case .number:
self.shared.add(rule: ValyRule.number)
case .minLength:
guard let min: Int = value1 as? Int else {
return self
}
self.shared.add(rule: ValyRule.minLength(min))
case .maxLength:
guard let max: Int = value1 as? Int else {
return self
}
self.shared.add(rule: ValyRule.maxLength(max))
case .exactLength:
guard let exact: Int = value1 as? Int else {
return self
}
self.shared.add(rule: ValyRule.exactLength(exact))
case .numericMin:
guard let min: Double = value1 as? Double else {
return self
}
self.shared.add(rule: ValyRule.numericMin(min))
case .numericMax:
guard let max: Double = value1 as? Double else {
return self
}
self.shared.add(rule: ValyRule.numericMax(max))
case .numericBetween:
guard let min: Double = value1 as? Double, let max: Double = value2 as? Double else {
return self
}
self.shared.add(rule: ValyRule.numericBetween(min: min, max: max))
}
return self
}
@objc(runWithValue:)
public func run(with value: String?) -> Bool {
guard let validatable: AnyValidatable = self.shared as? AnyValidatable else {
return false
}
switch validatable.run(with: value) {
case .success:
return true
case .failure(_):
return false
}
}
}
|
acb5b44805a77f5f76fcc276abf4d994
| 26.974138 | 97 | 0.557781 | false | false | false | false |
artursDerkintis/Starfly
|
refs/heads/master
|
Starfly/HistoryHit.swift
|
mit
|
1
|
//
// HistoryHit.swift
// Starfly
//
// Created by Arturs Derkintis on 3/16/16.
// Copyright © 2016 Starfly. All rights reserved.
//
import Foundation
import CoreData
@objc(HistoryHit)
class HistoryHit: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
var primitiveSectionIdentifier: String?
var primitiveSectionId : String?
var sectionId: String{
get {
return self.time!
}
set {
self.willChangeValueForKey("sectionID")
self.time = newValue
self.didChangeValueForKey("sectionID")
self.primitiveSectionIdentifier = nil
}
}
func setTimeAndDate(){
self.time = DateFormatter.sharedInstance.readableDate(NSDate())
self.arrangeIndex = CFAbsoluteTimeGetCurrent()
}
func getURL() -> NSURL{
if let url = self.urlOfIt{
return NSURL(string: url)!
}
return NSURL(string: "http://about:blank")!
}
lazy var icon : UIImage? = {
if let fav = self.faviconPath{
let iconFileName = (fav as NSString).lastPathComponent
let folder : NSString = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents/HistoryHit")
let iconPath = folder.stringByAppendingPathComponent(iconFileName as String)
if let icon = UIImage(contentsOfFile: iconPath) {
return icon
}
}
return nil
}()
func removeIcon(){
if let fav = self.faviconPath{
let stsAr : NSString? = (fav as NSString).lastPathComponent
let folder : NSString = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents/HistoryHit")
let path = folder.stringByAppendingPathComponent(stsAr! as String)
do {
try NSFileManager.defaultManager().removeItemAtPath(path)
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
func saveFavicon(image : UIImage){
if let data = UIImagePNGRepresentation(image){
let name : String = String(format: "%@.png", randomString(10))
let folder : String = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("Documents/HistoryHit")
if NSFileManager.defaultManager().fileExistsAtPath(folder) == false{
do {
try NSFileManager.defaultManager().createDirectoryAtPath(folder, withIntermediateDirectories: false, attributes: nil)
} catch _ {}
}
let newFilePath = String(format: (folder as NSString).stringByAppendingPathComponent(name))
data.writeToFile(newFilePath, atomically: true)
self.faviconPath = newFilePath
}
}
}
|
c97d0989a0b7013b13de39f8afa539aa
| 32.517241 | 137 | 0.608025 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/WordPressTest/MediaRequestAuthenticatorTests.swift
|
gpl-2.0
|
1
|
import XCTest
import OHHTTPStubs
@testable import WordPress
class MediaRequestAuthenticatorTests: CoreDataTestCase {
override func setUp() {
super.setUp()
contextManager.useAsSharedInstance(untilTestFinished: self)
}
// MARK: - Utility
func setupAccount(username: String, authToken: String) {
let account = ModelTestHelper.insertAccount(context: mainContext)
account.uuid = UUID().uuidString
account.userID = NSNumber(value: 156)
account.username = username
account.authToken = authToken
contextManager.saveContextAndWait(mainContext)
AccountService(managedObjectContext: mainContext).setDefaultWordPressComAccount(account)
}
fileprivate func stubResponse(forEndpoint endpoint: String, responseFilename filename: String) {
stub(condition: { request in
return (request.url!.absoluteString as NSString).contains(endpoint) && request.httpMethod! == "GET"
}) { _ in
let stubPath = OHPathForFile(filename, type(of: self))
return fixture(filePath: stubPath!, headers: ["Content-Type": "application/json"])
}
}
// MARK: - Tests
func testPublicSiteAuthentication() {
let url = URL(string: "http://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .publicSite,
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: { $0.key == "Authorization" }) ?? false
XCTAssertFalse(hasAuthorizationHeader)
XCTAssertEqual(request.url, url)
}) { error in
XCTFail("This should not be called")
}
}
func testPublicWPComSiteAuthentication() {
let url = URL(string: "http://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .publicSite,
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: { $0.key == "Authorization" }) ?? false
XCTAssertFalse(hasAuthorizationHeader)
XCTAssertEqual(request.url, url)
}) { error in
XCTFail("This should not be called")
}
}
/// This test only checks that the resulting URL is the origina URL for now. There's no special authentication
/// logic within `MediaRequestAuthenticator` for this case.
///
/// - TODO: consider bringing self-hosted private authentication logic into MediaRequestAuthenticator.
///
func testPrivateSelfHostedSiteAuthentication() {
let url = URL(string: "http://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .publicSite,
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: { $0.key == "Authorization" }) ?? false
XCTAssertFalse(hasAuthorizationHeader)
XCTAssertEqual(request.url, url)
}) { error in
XCTFail("This should not be called")
}
}
func testPrivateWPComSiteAuthentication() {
let authToken = "letMeIn!"
let url = URL(string: "http://www.wordpress.com")!
let expectedURL = URL(string: "https://www.wordpress.com")!
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .privateWPComSite(authToken: authToken),
onComplete: { request in
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: {
$0.key == "Authorization" && $0.value == "Bearer \(authToken)"
}) ?? false
XCTAssertTrue(hasAuthorizationHeader)
XCTAssertEqual(request.url, expectedURL)
}) { error in
XCTFail("This should not be called")
}
}
func testPrivateAtomicWPComSiteAuthentication() {
let username = "demouser"
let authToken = "letMeIn!"
let siteID = 15567
let url = URL(string: "http://www.wordpress.com")!
let expectedURL = URL(string: "https://www.wordpress.com")!
let expectation = self.expectation(description: "Completion closure called")
setupAccount(username: username, authToken: authToken)
let endpoint = "sites/\(siteID)/atomic-auth-proxy/read-access-cookies"
stubResponse(forEndpoint: endpoint, responseFilename: "atomic-get-authentication-cookie-success.json")
let authenticator = MediaRequestAuthenticator()
authenticator.authenticatedRequest(
for: url,
from: .privateAtomicWPComSite(siteID: siteID, username: username, authToken: authToken),
onComplete: { request in
expectation.fulfill()
let hasAuthorizationHeader = request.allHTTPHeaderFields?.contains(where: {
$0.key == "Authorization" && $0.value == "Bearer \(authToken)"
}) ?? false
XCTAssertTrue(hasAuthorizationHeader)
XCTAssertEqual(request.url, expectedURL)
}) { error in
XCTFail("This should not be called")
}
waitForExpectations(timeout: 0.5)
}
}
|
5988b75e17e7d89835623458e61c9765
| 37.296552 | 129 | 0.625968 | false | true | false | false |
jeesmon/varamozhi-ios
|
refs/heads/master
|
varamozhi/DefaultKeyboard.swift
|
gpl-2.0
|
1
|
//
// DefaultKeyboard.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
func defaultKeyboard() -> Keyboard {
let defaultKeyboard = Keyboard()
for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 0)
}
//+20141212 starting ipad
let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
if isPad {
let backspace = Key(.backspace)
defaultKeyboard.addKey(backspace, row: 0, page: 0)
}
for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 0)
}
let returnKey = Key(.return)
returnKey.uppercaseKeyCap = "return"
returnKey.uppercaseOutput = "\n"
returnKey.lowercaseOutput = "\n"
if isPad {
defaultKeyboard.addKey(returnKey, row: 1, page: 0)
}
let keyModel = Key(.shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
for key in ["Z", "X", "C", "V", "B", "N", "M"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}
if isPad {
let m1 = Key(.specialCharacter)
m1.uppercaseKeyCap = "!\n,"
m1.uppercaseOutput = "!"
m1.lowercaseOutput = ","
defaultKeyboard.addKey(m1, row: 2, page: 0)
let m2 = Key(.specialCharacter)
m2.uppercaseKeyCap = "?\n."
m2.uppercaseOutput = "?"
m2.lowercaseOutput = "."
defaultKeyboard.addKey(m2, row: 2, page: 0)
let keyModel = Key(.shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}else{
let backspace = Key(.backspace)
defaultKeyboard.addKey(backspace, row: 2, page: 0)
}
let keyModeChangeNumbers = Key(.modeChange)
keyModeChangeNumbers.uppercaseKeyCap = "123"
keyModeChangeNumbers.toMode = 1
defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0)
let keyboardChange = Key(.keyboardChange)
defaultKeyboard.addKey(keyboardChange, row: 3, page: 0)
//let settings = Key(.Settings)
//defaultKeyboard.addKey(settings, row: 3, page: 0)
let tildeModel = Key(.specialCharacter)
tildeModel.setLetter("~")
defaultKeyboard.addKey(tildeModel, row: 3, page: 0)
let space = Key(.space)
space.uppercaseKeyCap = "space"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(space, row: 3, page: 0)
let usModel = Key(.specialCharacter)
usModel.setLetter("_")
defaultKeyboard.addKey(usModel, row: 3, page: 0)
if isPad {
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 3, page: 0)
let dismiss = Key(.dismiss)
defaultKeyboard.addKey(dismiss, row: 3, page: 0)
}else{
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 0)
}
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 1)
}
if isPad {
defaultKeyboard.addKey(Key(.backspace), row: 0, page: 1)
}
let cl = Locale.current
let symbol: NSString? = (cl as NSLocale).object(forKey: NSLocale.Key.currencySymbol) as? NSString
var c = "₹"
if symbol != nil {
c = symbol! as String
}
for key in ["-", "/", ":", ";", "(", ")", c, "&", "@"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
if isPad {
defaultKeyboard.addKey(Key(returnKey), row: 1, page: 1)
}else{
let keyModel = Key(.specialCharacter)
keyModel.setLetter("\"")
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
let keyModeChangeSpecialCharacters = Key(.modeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1)
for key in [".", ",", "?", "!", "'"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
}
if isPad {
let keyModel = Key(.specialCharacter)
keyModel.setLetter("\"")
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
let keyModeChangeSpecialCharacters2 = Key(.modeChange)
keyModeChangeSpecialCharacters2.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters2.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters2, row: 2, page: 1)
}else{
defaultKeyboard.addKey(Key(.backspace), row: 2, page: 1)
}
let keyModeChangeLetters = Key(.modeChange)
keyModeChangeLetters.uppercaseKeyCap = "ABC"
keyModeChangeLetters.toMode = 0
defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 1)
//defaultKeyboard.addKey(Key(settings), row: 3, page: 1)
defaultKeyboard.addKey(Key(space), row: 3, page: 1)
if isPad {
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 1)
let dismiss = Key(.dismiss)
defaultKeyboard.addKey(dismiss, row: 3, page: 1)
}else{
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1)
}
for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 2)
}
if isPad {
defaultKeyboard.addKey(Key(.backspace), row: 0, page: 2)
}
var d = "£"
if c == "₹" {
c = "$"
}else if c == "$" {
c = "₹"
}else{
d = "$"
c = "₹"
}
for key in ["_", "\\", "|", "~", "<", ">", c, d, "€"] {// ¥
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
if isPad {
defaultKeyboard.addKey(Key(returnKey), row: 1, page: 2)
}else{
let keyModel = Key(.specialCharacter)
keyModel.setLetter("•")
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
for key in [".", ",", "?", "!", "'"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
}
if isPad {
let keyModel = Key(.specialCharacter)
keyModel.setLetter("\"")
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
}else{
defaultKeyboard.addKey(Key(.backspace), row: 2, page: 2)
}
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 2)
//defaultKeyboard.addKey(Key(settings), row: 3, page: 2)
defaultKeyboard.addKey(Key(space), row: 3, page: 2)
if isPad {
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
let dismiss = Key(.dismiss)
defaultKeyboard.addKey(dismiss, row: 3, page: 2)
}else{
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 2)
}
return defaultKeyboard
}
|
05d2d1dc130bbb8a65a9e30476ef4813
| 27.785714 | 101 | 0.569479 | false | false | false | false |
kellanburket/Passenger
|
refs/heads/master
|
Pod/Classes/Extensions/String.swift
|
mit
|
1
|
//
// Functions.swift
// Pods
//
// Created by Kellan Cummings on 6/10/15.
//
//
import Foundation
import Wildcard
import CommonCrypto
internal let MIMEBase64Encoding: [Character] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"+", "/"
]
internal let WhitelistedPercentEncodingCharacters: [UnicodeScalar] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
".", "-", "_", "~"
]
internal extension String {
internal func sign(algorithm: HMACAlgorithm, key: String) -> String? {
if let data = self.dataUsingEncoding(NSUTF8StringEncoding) {
return data.sign(algorithm, key: key)
}
return nil
}
internal var base64Encoded: String {
var encoded: String = ""
var base: UInt64 = 0
var i: UInt64 = 0
var padding: String = ""
for character in self.unicodeScalars {
if i < 3 {
base = base << 8 | UInt64(character)
++i
} else {
for i = 3; i > 0; --i {
let bitmask: UInt64 = 0b111111 << (i * 6)
encoded.append(
MIMEBase64Encoding[Int((bitmask & base) >> (i * 6))]
)
}
encoded.append(
MIMEBase64Encoding[Int(0b111111 & base)]
)
base = UInt64(character)
i = 1
}
}
let remainder = Int(3 - i)
for var j = 0; j < remainder; ++j {
padding += "="
base <<= 2
}
let iterations: UInt64 = (remainder == 2) ? 1 : 2
for var k: UInt64 = iterations ; k > 0; --k {
let bitmask: UInt64 = 0b111111 << (k * 6)
encoded.append(
MIMEBase64Encoding[Int((bitmask & base) >> (k * 6))]
)
}
encoded.append(
MIMEBase64Encoding[Int(0b111111 & base)]
)
return encoded + padding
}
internal var urlEncoded: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
}
internal func percentEncode(ignore: [UnicodeScalar] = [UnicodeScalar]()) -> String {
var output = ""
for char in self.unicodeScalars {
if contains(WhitelistedPercentEncodingCharacters, char) || contains(ignore, char) {
output.append(char)
} else {
output += String(format: "%%%02X", UInt64(char))
}
}
return output
}
internal func encode(encoding: UInt = NSUTF8StringEncoding, allowLossyConversion: Bool = true) -> NSData? {
return self.dataUsingEncoding(encoding, allowLossyConversion: allowLossyConversion)
}
}
|
2a061cfb4c3844a636259e479619bcde
| 30.66055 | 133 | 0.44277 | false | false | false | false |
mmrmmlrr/HandyText
|
refs/heads/master
|
Demo/HandyTextExample/HandyTextExample/ApplicationStyles.swift
|
mit
|
1
|
//
// ApplicationStyles.swift
// TextStyleExample
//
// Created by Aleksey on 04.07.16.
// Copyright © 2016 Aleksey Chernish. All rights reserved.
//
import UIKit
extension TextStyle {
static var plainText: TextStyle {
return TextStyle(font: .helvetica).withSize(12)
}
static var url: TextStyle {
return plainText.withForegroundColor(.blue).italic().withUnderline(.single)
}
static var header: TextStyle {
return plainText.withSizeMultiplied(by: 1.4).withForegroundColor(.orange).uppercase().bold()
}
static var button: TextStyle {
let shadow = NSShadow()
shadow.shadowOffset = CGSize(width: 1.0, height: 1.0)
shadow.shadowBlurRadius = 1.0
shadow.shadowColor = UIColor.lightGray
return header.withForegroundColor(.black).withShadow(shadow)
}
}
extension TagScheme {
static var `default`: TagScheme {
let scheme = TagScheme()
scheme.forTag("b") { $0.bold() }
scheme.forTag("i") { $0.italic().withUnderline(.single) }
scheme.forTag("u") { $0.uppercase() }
return scheme
}
}
|
841cdfc0e5e1466a429ac17a148ef634
| 21.893617 | 96 | 0.674721 | false | false | false | false |
yinhaofrancis/YHAlertView
|
refs/heads/master
|
YHKit/YHAlertButton.swift
|
mit
|
1
|
//
// YHAlertButton.swift
// YHAlertView
//
// Created by hao yin on 2017/5/28.
// Copyright © 2017年 yyk. All rights reserved.
//
import UIKit
// MARK: - call back action
public typealias YHActionCallBack = ()->Void
public enum YHButtonStyle{
case title(title:String,action:YHActionCallBack?,style:YHViewStyle<UIButton>?)
case image(image:UIImage,action:YHActionCallBack?,style:YHViewStyle<UIButton>?)
}
class holdAction:NSObject{
func callblock(){
block?()
}
var block:(()->Void)?
}
extension UIButton{
public convenience init(action:YHButtonStyle){
self.init(frame: CGRect.zero)
let s = "\(Date().timeIntervalSince1970)-\(arc4random())"
switch action {
case let .title(title: t, action: call,style:st):
self.setTitle(t, for: .normal)
st?(self)
if let c = call{
self.addTarget(key: s, call: c, event: .touchUpInside)
}
case let .image(image: img, action: call,style:st):
self.setImage(img, for: .normal)
st?(self)
if let c = call{
self.addTarget(key: s, call: c, event: .touchUpInside)
}
}
}
}
extension UIControl {
private struct obj{
static var dic:[String:holdAction] = [:]
}
var mapAction:[String:holdAction]{
get{
return (objc_getAssociatedObject(self, &obj.dic) as? [String : holdAction]) ?? [:]
}
set{
objc_setAssociatedObject(self, &obj.dic, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func addTarget(key:String,call:@escaping ()->Void,event:UIControlEvents){
let hold = holdAction()
self.mapAction[key] = hold
hold.block = call
self.addTarget(hold, action: #selector(hold.callblock), for: event)
}
}
|
04a455151ff5e36e63dd342dd2429aef
| 26.101449 | 98 | 0.590909 | false | false | false | false |
mendesbarreto/IOS
|
refs/heads/master
|
UICollectionInUITableViewCell/UICollectionInUITableViewCell/NSDate.swift
|
mit
|
1
|
//
// NSDate.swift
// UICollectionInUITableViewCell
//
// Created by Douglas Barreto on 2/24/16.
// Copyright © 2016 CoderKingdom. All rights reserved.
//
import Foundation
// MARK Enums
public enum WeekDays: Int {
case Sunday = 1
case Monday = 2
case Tuesday = 3
case Wednesday = 4
case Thursday = 5
case Friday = 6
case Saturday = 7
}
// MARK Consts
let secondsPerDay:Double = 24 * 60 * 60 ;
let secondsPerWeek:Double = secondsPerDay * 7
let secondsPerMonth:Double = secondsPerWeek * 4
// MARK Extension
extension NSDate {
func nextDay() -> NSDate {
return self.dateByAddingTimeInterval(secondsPerDay)
}
func lastDay() -> NSDate {
return self.dateByAddingTimeInterval(-secondsPerDay)
}
func lastWeek() -> NSDate {
return self.dateByAddingTimeInterval(-secondsPerWeek)
}
func nextWeek() -> NSDate {
return self.dateByAddingTimeInterval(secondsPerWeek)
}
func forwardWeek( weeks:Int ) -> NSDate {
return self.forward(days: weeks * 7)
}
func backwardWeek( weeks:Int ) -> NSDate {
return self.backward(days: weeks * 7)
}
func forward( days days:Int ) -> NSDate {
return self.dateByAddingTimeInterval( NSTimeInterval( secondsPerDay * Double(days) ) )
}
func backward( days days:Int ) -> NSDate {
return self.dateByAddingTimeInterval( NSTimeInterval( -( secondsPerDay * Double(days) ) ) )
}
func beginOfMonth() -> NSDate {
let componet = self.createDateComponents()
componet.day -= componet.day - 1
return componet.date!
}
func endOfWeek() -> NSDate {
return self.forward(days: WeekDays.Saturday.rawValue - self.weekday().rawValue)
}
func beginOfWeek() -> NSDate {
return self.forward(days: WeekDays.Sunday.rawValue - self.weekday().rawValue)
}
func gotoMonday() ->NSDate {
return self.forward(days: WeekDays.Monday.rawValue - self.weekday().rawValue)
}
func weekday() -> WeekDays {
let weekDay = self.createDateComponents(components: NSCalendarUnit.Weekday ).weekday
return WeekDays(rawValue: weekDay)!
}
func day() -> Int {
return self.createDateComponents(components: NSCalendarUnit.Day ).day
}
func month() -> Int {
return self.createDateComponents(components: NSCalendarUnit.Month ).month
}
func year() -> Int {
return self.createDateComponents(components: NSCalendarUnit.Year ).year
}
func createDateComponents(components components: NSCalendarUnit? = nil, calendar:NSCalendar? = nil ) -> NSDateComponents {
let ca: NSCalendar
if let calTemp = calendar {
ca = calTemp
} else {
ca = NSCalendar.currentCalendar()
}
if let co = components {
return ca.components(co, fromDate: self)
}
return ca.components([
NSCalendarUnit.Weekday,
NSCalendarUnit.Day,
NSCalendarUnit.Calendar,
NSCalendarUnit.Month,
NSCalendarUnit.Year,
NSCalendarUnit.WeekOfYear,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Second,
NSCalendarUnit.Nanosecond], fromDate: self)
}
func isWeekDay( weekDay:WeekDays ) -> Bool {
return self.weekday() == weekDay
}
func weekDayName( localeIdentifier localeId:String? = nil ) -> String {
let dateFormatter = NSDateFormatter()
let locale: NSLocale
if let localeIdentifier: String = localeId {
locale = NSLocale(localeIdentifier: localeIdentifier)
} else {
if let preferred: String = NSLocale.preferredLanguages().first {
locale = NSLocale(localeIdentifier: preferred)
} else {
locale = NSLocale(localeIdentifier: "pt_br")
}
}
dateFormatter.dateFormat = "EEEE"
dateFormatter.locale = locale
return dateFormatter.stringFromDate(self)
}
func weekdayPrefix(length length:Int, localeIdentifier localeId:String? = nil ) -> String {
let weekDayName = self.weekDayName(localeIdentifier: localeId)
let usedLength: Int
let range: Range<String.Index>
if( length > weekDayName.characters.count ) {
usedLength = weekDayName.characters.count
} else {
usedLength = length
}
range = Range<String.Index>(start: weekDayName.startIndex, end: weekDayName.startIndex.advancedBy(usedLength))
return weekDayName.substringWithRange(range)
}
}
|
2b8c1cb8389cc90761223c75289eace6
| 23.975758 | 124 | 0.714147 | false | false | false | false |
rchatham/SwiftyAnimate
|
refs/heads/master
|
Tests/SwiftyAnimateTests/FinishAnimationTests.swift
|
mit
|
1
|
//
// FinishAnimationTests.swift
// SwiftyAnimate
//
// Created by Reid Chatham on 2/4/17.
// Copyright © 2017 Reid Chatham. All rights reserved.
//
import XCTest
@testable import SwiftyAnimate
class FinishAnimationTests: XCTestCase {
func test_EmptyAnimate_Finished() {
var finishedAnimation = false
let animation = Animate()
XCTAssertFalse(finishedAnimation)
animation.finish(duration: 0.5) {
finishedAnimation = true
}
XCTAssertTrue(finishedAnimation)
}
func test_EmptyAnimate_Finished_Animation() {
var finishedAnimation = false
let animation = Animate(duration: 0.5) {
finishedAnimation = true
}
XCTAssertFalse(finishedAnimation)
Animate().finish(animation: animation)
XCTAssertTrue(finishedAnimation)
}
func test_EmptyAnimate_Finished_Keyframe() {
var finishedAnimation = false
let animation = Animate()
XCTAssertFalse(finishedAnimation)
let keyframe = KeyframeAnimation(keyframes: [
Keyframe(duration: 1.0) {
finishedAnimation = true
}], options: [])
animation.finish(animation: keyframe)
XCTAssertTrue(finishedAnimation)
}
}
|
95060053c2db1368bf8bcebe10dcb495
| 22.145161 | 55 | 0.570035 | false | true | false | false |
wdkk/CAIM
|
refs/heads/master
|
Basic/answer/caim05_1effect_A/basic/DrawingViewController.swift
|
mit
|
1
|
//
// DrawingViewController.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import UIKit
class DrawingViewController : CAIMViewController
{
// view_allを画面いっぱいのピクセル領域(screenPixelRect)の大きさで用意
var view_all:CAIMView = CAIMView(pixelFrame: CAIM.screenPixelRect)
// 画像データimg_allを画面のピクセルサイズ(screenPixelSize)に合わせて用意
var img_all:CAIMImage = CAIMImage(size: CAIM.screenPixelSize)
// パーティクル情報の構造体
struct Particle {
var cx:Int = 0
var cy:Int = 0
var radius:Int = 0
var color:CAIMColor = CAIMColor(R: 0.0, G: 0.0, B: 0.0, A: 1.0)
var step:Float = 0.0
}
// パーティクル群を保存しておく配列
var parts:[Particle] = [Particle]()
// 新しいパーティクル情報を作り、返す関数
func generateParticle() -> Particle {
let wid:Int = img_all.width
let hgt:Int = img_all.height
// 位置(cx,cy)、半径(radius)、色(color)を指定した範囲のランダム値で設定
var p = Particle()
p.cx = Int(arc4random()) % wid
p.cy = Int(arc4random()) % hgt
p.radius = Int(arc4random()) % 40 + 20
p.color = CAIMColor(
R: Float(arc4random() % 1000)/1000.0,
G: Float(arc4random() % 1000)/1000.0,
B: Float(arc4random() % 1000)/1000.0,
A: 1.0)
// 作成したパーティクル情報を返す
return p
}
// 準備
override func setup() {
// img_allを白で塗りつぶす
img_all.fillColor( CAIMColor.white )
// view_allの画像として、img_allを設定する
view_all.image = img_all
// view_allを画面に追加
self.view.addSubview( view_all )
// パーティクルを20個作成
for _ in 0 ..< 20 {
var p = generateParticle()
p.step = Float(arc4random() % 1000)/1000.0
parts.append(p)
}
}
// ポーリング
override func update() {
// 毎フレームごと、はじめにimg_allを白で塗りつぶす
img_all.fillColor( CAIMColor.white )
// parts内のパーティクル情報をすべてスキャンする
for i in 0 ..< parts.count {
// 1回処理をするごとにstepを0.01足す
parts[i].step += 0.01
// stepがマイナスの値の場合処理せず、次のパーティクルに移る
if(parts[i].step < 0.0) { continue }
// stepが1.0以上になったら、現在のパーティクル(parts[i])は処理を終えたものとする
// 次に、parts[i]はgenerateParticle()から新しいパーティクル情報を受け取り、新パーティクルとして再始動する
// parts[i]のstepを0.0に戻して初期化したのち、この処理は中断して次のパーティクルに移る
if(parts[i].step >= 1.0) {
parts[i] = generateParticle()
parts[i].step = 0.0
continue
}
// 不透明度(opacity)はstep=0.0~0.5の増加に合わせて最大まで濃くなり、0.5~1.0までに最小まで薄くなる
var opacity:Float = 0.0
if(parts[i].step < 0.5) { opacity = parts[i].step * 2.0 }
else { opacity = (1.0 - parts[i].step) * 2.0 }
// 半径は基本半径(parts[i].radius)にstepと係数2.0を掛け算する
let radius:Int = Int(Float(parts[i].radius) * parts[i].step * 2.0)
// パーティクル情報から求めた計算結果を用いてドームを描く
ImageToolBox.fillDomeFast(img_all, cx: parts[i].cx, cy: parts[i].cy,
radius: radius, color: parts[i].color, opacity: opacity)
}
// 画像が更新されている可能性があるので、view_allを再描画して結果を表示
view_all.redraw()
}
}
|
9bf6b759e4ba586f77c360ac3a938db5
| 30.155963 | 80 | 0.555948 | false | false | false | false |
IvanKalaica/GitHubSearch
|
refs/heads/master
|
GitHubSearch/GitHubSearch/Model/Service/GitHub/DefaultOAuthService.swift
|
mit
|
1
|
//
// DefaultOAuthService.swift
// GitHubSearch
//
// Created by Ivan Kalaica on 23/09/2017.
// Copyright © 2017 Kalaica. All rights reserved.
//
import Foundation
import Alamofire
import OAuth2
import RxSwift
struct DefaultOAuthService: OAuthService {
private let oAuth2CodeGrant: OAuth2CodeGrant
init() {
self.oAuth2CodeGrant = OAuth2CodeGrant(settings: [
"client_id": GitHubOAuth.clientId,
"client_secret": GitHubOAuth.clientSecret,
"authorize_uri": GitHubOAuth.authorizeUri,
"token_uri": GitHubOAuth.tokenUri,
"redirect_uris": GitHubOAuth.redirectUris,
"scope": GitHubOAuth.scope,
"secret_in_body": GitHubOAuth.secretInBody,
"keychain": GitHubOAuth.keychain,
] as OAuth2JSON)
let sessionManager = SessionManager.default
let retrier = OAuth2RetryHandler(oauth2: self.oAuth2CodeGrant)
sessionManager.adapter = retrier
sessionManager.retrier = retrier
}
func authorize() -> Observable<Void> {
return Observable.create { observer in
self.oAuth2CodeGrant.authorize() { authParameters, error in
guard let sError = error else {
print("Authorized! Access token is in `oauth2.accessToken`")
print("Authorized! Additional parameters: \(String(describing: authParameters))")
observer.onNext()
observer.onCompleted()
return
}
print("Authorization was canceled or went wrong: \(String(describing: sError))")
observer.onError(sError)
}
return Disposables.create()
}
}
func logout() {
self.oAuth2CodeGrant.forgetTokens()
let storage = HTTPCookieStorage.shared
storage.cookies?.forEach() { storage.deleteCookie($0) }
}
func handleRedirectURL(_ url: URL) {
self.oAuth2CodeGrant.handleRedirectURL(url)
}
}
|
d0cfc3f24598c7e40f26f808785966f9
| 33.233333 | 101 | 0.609542 | false | false | false | false |
becvert/cordova-plugin-zeroconf
|
refs/heads/master
|
src/ios/ZeroConf.swift
|
mit
|
1
|
import Foundation
@objc(ZeroConf) public class ZeroConf : CDVPlugin {
fileprivate var publishers: [String: Publisher]!
fileprivate var browsers: [String: Browser]!
override public func pluginInitialize() {
publishers = [:]
browsers = [:]
}
override public func onAppTerminate() {
for (_, publisher) in publishers {
publisher.destroy()
}
publishers.removeAll()
for (_, browser) in browsers {
browser.destroy();
}
browsers.removeAll()
}
@objc public func getHostname(_ command: CDVInvokedUrlCommand) {
let hostname = Hostname.get() as String
#if DEBUG
print("ZeroConf: hostname \(hostname)")
#endif
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK, messageAs: hostname)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
@objc public func register(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
let name = command.argument(at: 2) as! String
let port = command.argument(at: 3) as! Int
#if DEBUG
print("ZeroConf: register \(name + "." + type + domain)")
#endif
var txtRecord: [String: Data]?
if let dict = command.arguments[4] as? [String: String] {
txtRecord = [:]
for (key, value) in dict {
txtRecord?[key] = value.data(using: String.Encoding.utf8)
}
}
let publisher = Publisher(withDomain: domain, withType: type, withName: name, withPort: port, withTxtRecord: txtRecord, withCallbackId: command.callbackId)
publisher.commandDelegate = commandDelegate
publisher.register()
publishers[name + "." + type + domain] = publisher
}
@objc public func unregister(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
let name = command.argument(at: 2) as! String
#if DEBUG
print("ZeroConf: unregister \(name + "." + type + domain)")
#endif
if let publisher = publishers[name + "." + type + domain] {
publisher.unregister();
publishers.removeValue(forKey: name + "." + type + domain)
}
}
@objc public func stop(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("ZeroConf: stop")
#endif
for (_, publisher) in publishers {
publisher.unregister()
}
publishers.removeAll()
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
@objc public func watch(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
#if DEBUG
print("ZeroConf: watch \(type + domain)")
#endif
let browser = Browser(withDomain: domain, withType: type, withCallbackId: command.callbackId)
browser.commandDelegate = commandDelegate
browser.watch()
browsers[type + domain] = browser
}
@objc public func unwatch(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
#if DEBUG
print("ZeroConf: unwatch \(type + domain)")
#endif
if let browser = browsers[type + domain] {
browser.unwatch();
browsers.removeValue(forKey: type + domain)
}
}
@objc public func close(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("ZeroConf: close")
#endif
for (_, browser) in browsers {
browser.unwatch()
}
browsers.removeAll()
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
@objc public func reInit(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("ZeroConf: reInit")
#endif
// Terminate
for (_, publisher) in publishers {
publisher.destroy()
}
publishers.removeAll()
for (_, browser) in browsers {
browser.destroy();
}
browsers.removeAll()
// init
publishers = [:]
browsers = [:]
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
internal class Publisher: NSObject, NetServiceDelegate {
var nsp: NetService?
var domain: String
var type: String
var name: String
var port: Int
var txtRecord: [String: Data]?
var callbackId: String
var commandDelegate: CDVCommandDelegate?
init (withDomain domain: String, withType type: String, withName name: String, withPort port: Int, withTxtRecord txtRecord: [String: Data]?, withCallbackId callbackId: String) {
self.domain = domain
self.type = type
self.name = name
self.port = port
self.txtRecord = txtRecord
self.callbackId = callbackId
}
func register() {
// Netservice
let service = NetService(domain: domain, type: type , name: name, port: Int32(port))
nsp = service
service.delegate = self
if let record = txtRecord {
if record.count > 0 {
service.setTXTRecord(NetService.data(fromTXTRecord: record))
}
}
commandDelegate?.run(inBackground: {
service.publish()
})
}
func unregister() {
if let service = nsp {
service.stop()
}
}
func destroy() {
if let service = nsp {
service.stop()
}
}
@objc func netServiceDidPublish(_ netService: NetService) {
#if DEBUG
print("ZeroConf: netService:didPublish:\(netService)")
#endif
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["registered", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netService(_ netService: NetService, didNotPublish errorDict: [String : NSNumber]) {
#if DEBUG
print("ZeroConf: netService:didNotPublish:\(netService) \(errorDict)")
#endif
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceDidStop(_ netService: NetService) {
nsp = nil
commandDelegate = nil
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
}
internal class Browser: NSObject, NetServiceDelegate, NetServiceBrowserDelegate {
var nsb: NetServiceBrowser?
var domain: String
var type: String
var callbackId: String
var services: [String: NetService] = [:]
var commandDelegate: CDVCommandDelegate?
init (withDomain domain: String, withType type: String, withCallbackId callbackId: String) {
self.domain = domain
self.type = type
self.callbackId = callbackId
}
func watch() {
// Net service browser
let browser = NetServiceBrowser()
nsb = browser
browser.delegate = self
commandDelegate?.run(inBackground: {
browser.searchForServices(ofType: self.type, inDomain: self.domain)
})
let pluginResult = CDVPluginResult(status: CDVCommandStatus_NO_RESULT)
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
func unwatch() {
if let service = nsb {
service.stop()
}
}
func destroy() {
if let service = nsb {
service.stop()
}
}
@objc func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
#if DEBUG
print("ZeroConf: netServiceBrowser:didNotSearch:\(netService) \(errorDict)")
#endif
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didFind netService: NetService,
moreComing moreServicesComing: Bool) {
#if DEBUG
print("ZeroConf: netServiceBrowser:didFindService:\(netService)")
#endif
netService.delegate = self
netService.resolve(withTimeout: 5000)
services[netService.name] = netService // keep strong reference to catch didResolveAddress
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["added", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceDidResolveAddress(_ netService: NetService) {
#if DEBUG
print("ZeroConf: netService:didResolveAddress:\(netService)")
#endif
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["resolved", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netService(_ netService: NetService, didNotResolve errorDict: [String : NSNumber]) {
#if DEBUG
print("ZeroConf: netService:didNotResolve:\(netService) \(errorDict)")
#endif
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didRemove netService: NetService,
moreComing moreServicesComing: Bool) {
#if DEBUG
print("ZeroConf: netServiceBrowser:didRemoveService:\(netService)")
#endif
services.removeValue(forKey: netService.name)
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["removed", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceDidStop(_ netService: NetService) {
nsb = nil
services.removeAll()
commandDelegate = nil
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
}
fileprivate static func jsonifyService(_ netService: NetService) -> NSDictionary {
var ipv4Addresses: [String] = []
var ipv6Addresses: [String] = []
for address in netService.addresses! {
if let family = extractFamily(address) {
if family == 4 {
if let addr = extractAddress(address) {
ipv4Addresses.append(addr)
}
} else if family == 6 {
if let addr = extractAddress(address) {
ipv6Addresses.append(addr)
}
}
}
}
if ipv6Addresses.count > 1 {
ipv6Addresses = Array(Set(ipv6Addresses))
}
var txtRecord: [String: String] = [:]
if let txtRecordData = netService.txtRecordData() {
txtRecord = dictionary(fromTXTRecord: txtRecordData)
}
var hostName:String = ""
if netService.hostName != nil {
hostName = netService.hostName!
}
let service: NSDictionary = NSDictionary(
objects: [netService.domain, netService.type, netService.name, netService.port, hostName, ipv4Addresses, ipv6Addresses, txtRecord],
forKeys: ["domain" as NSCopying, "type" as NSCopying, "name" as NSCopying, "port" as NSCopying, "hostname" as NSCopying, "ipv4Addresses" as NSCopying, "ipv6Addresses" as NSCopying, "txtRecord" as NSCopying])
return service
}
fileprivate static func extractFamily(_ addressBytes:Data) -> Int? {
let addr = (addressBytes as NSData).bytes.load(as: sockaddr.self)
if (addr.sa_family == sa_family_t(AF_INET)) {
return 4
}
else if (addr.sa_family == sa_family_t(AF_INET6)) {
return 6
}
else {
return nil
}
}
fileprivate static func extractAddress(_ addressBytes:Data) -> String? {
var addr = (addressBytes as NSData).bytes.load(as: sockaddr.self)
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname,
socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0) {
return String(cString: hostname)
}
return nil
}
fileprivate static func dictionary(fromTXTRecord txtData: Data) -> [String: String] {
var result = [String: String]()
var data = txtData
while !data.isEmpty {
// The first byte of each record is its length, so prefix that much data
let recordLength = Int(data.removeFirst())
guard data.count >= recordLength else { return [:] }
let recordData = data[..<(data.startIndex + recordLength)]
data = data.dropFirst(recordLength)
guard let record = String(bytes: recordData, encoding: .utf8) else { return [:] }
// The format of the entry is "key=value"
// (According to the reference implementation, = is optional if there is no value,
// and any equals signs after the first are part of the value.)
// `ommittingEmptySubsequences` is necessary otherwise an empty string will crash the next line
let keyValue = record.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
let key = String(keyValue[0])
// If there's no value, make the value the empty string
switch keyValue.count {
case 1:
result[key] = ""
case 2:
result[key] = String(keyValue[1])
default:
fatalError("ZeroConf: Malformed or unexpected TXTRecord keyValue")
}
}
return result
}
}
|
01cf8ce34ca39354b79113c9483336c3
| 33.871795 | 219 | 0.587255 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.