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
Shimmen/CoreDataTests
refs/heads/master
CoreDataTest-1/CoreDataTest-1/ViewController.swift
mit
1
// // ViewController.swift // CoreDataTest-1 // // Created by Simon Moos on 06/11/14. // import UIKit import CoreData class ViewController: UITableViewController { var people: [Person] = [Person]() // Returns the managed object context from the AppDelegate var managedObjectContext: NSManagedObjectContext { let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate return appDelegate.managedObjectContext! } // MARK: - View Controller lifecycle override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Building table view override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell let person = people[indexPath.row] cell.textLabel.text = person.identification return cell } // MARK: - Editing table view override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { removePersonAtIndexPath(indexPath) } } // MARK: - Adding and removing cells @IBAction func addNewPerson() { // Create Person (with default values for all attributes) in database let personEntity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedObjectContext) // Create a Person from the entity so custom properites/attributes can be set var person = Person(entity: personEntity!, insertIntoManagedObjectContext: managedObjectContext) // Set properties/attributes person.firstName = "Firsname" person.lastName = "Lastname" person.age = NSDate().timeIntervalSince1970 // Just to get some unique number // Add to data source list and tell table view to update those rows let indexPath = NSIndexPath(forRow: 0, inSection: 0) people.insert(person, atIndex: indexPath.row) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } func removePersonAtIndexPath(indexPath: NSIndexPath) { // Remove from database managedObjectContext.deleteObject(people[indexPath.row]) // Remove from table view and people array people.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } }
89734264c8bc36febf22db25560dfe35
30.21
155
0.67158
false
false
false
false
johnno1962/GitDiff
refs/heads/master
SharedXPC/LineGenerators.swift
mit
2
// // LineGenerators.swift // refactord // // Created by John Holdsworth on 19/12/2015. // Copyright © 2015 John Holdsworth. All rights reserved. // // $Id: //depot/Refactorator/refactord/LineGenerators.swift#7 $ // // Repo: https://github.com/johnno1962/Refactorator // import Foundation open class TaskGenerator: FileGenerator { let task: Process convenience init(command: String, directory: String? = nil, lineSeparator: String? = nil) { self.init(launchPath: "/bin/bash", arguments: ["-c", "exec \(command)"], directory: directory, lineSeparator: lineSeparator) } convenience init(launchPath: String, arguments: [String] = [], directory: String? = nil, lineSeparator: String? = nil) { let task = Process() task.launchPath = launchPath task.arguments = arguments task.currentDirectoryPath = directory ?? "." self.init(task: task, lineSeparator: lineSeparator) } init(task: Process, lineSeparator: String? = nil) { self.task = task let pipe = Pipe() task.standardOutput = pipe.fileHandleForWriting task.launch() pipe.fileHandleForWriting.closeFile() super.init(handle: pipe.fileHandleForReading, lineSeparator: lineSeparator) } deinit { task.terminate() } } open class FileGenerator: IteratorProtocol { let eol: Int32 let handle: FileHandle let readBuffer = NSMutableData() convenience init?(path: String, lineSeparator: String? = nil) { guard let handle = FileHandle(forReadingAtPath: path) else { return nil } self.init(handle: handle, lineSeparator: lineSeparator) } init(handle: FileHandle, lineSeparator: String? = nil) { eol = Int32((lineSeparator ?? "\n").utf16.first!) self.handle = handle } open func next() -> String? { while true { if let endOfLine = memchr(readBuffer.bytes, eol, readBuffer.length) { let endOfLine = endOfLine.assumingMemoryBound(to: Int8.self) endOfLine[0] = 0 let start = readBuffer.bytes.assumingMemoryBound(to: Int8.self) let line = String(cString: start) let consumed = NSMakeRange(0, UnsafePointer<Int8>(endOfLine) + 1 - start) readBuffer.replaceBytes(in: consumed, withBytes: nil, length: 0) return line } let bytesRead = handle.availableData if bytesRead.count <= 0 { if readBuffer.length != 0 { let last = String.fromData(data: readBuffer) readBuffer.length = 0 return last } else { break } } readBuffer.append(bytesRead) } return nil } open var lineSequence: AnySequence<String> { return AnySequence({ self }) } deinit { handle.closeFile() } } extension String { static func fromData(data: NSData, encoding: String.Encoding = .utf8) -> String? { return String(data: data as Data, encoding: encoding) } }
1db5aef462f9fe39937deca48e296a11
26.973684
124
0.596425
false
false
false
false
mansoor92/MaksabComponents
refs/heads/master
MaksabComponents/Classes/Navigation Controller/MaksabNavigationController.swift
mit
1
// // MaksabNavigationController.swift // Pods // // Created by Incubasys on 20/07/2017. // // import UIKit import StylingBoilerPlate open class MaksabNavigationController: UINavigationController { @IBInspectable public var isTransparent: Bool = true { didSet{ setBarStyle(_isTransparent: isTransparent) } } override open func viewDidLoad() { super.viewDidLoad() setBarStyle(_isTransparent: isTransparent) self.navigationBar.topItem?.title = "" } func setBarStyle(_isTransparent: Bool) { if _isTransparent{ let img = UIImage.getImageFromColor(color: UIColor.clear, size: CGSize(width: self.view.frame.size.width, height: 64)) self.navigationBar.setBackgroundImage(img, for: .default) let shadowImg = UIImage.getImageFromColor(color: UIColor.clear, size: CGSize(width: self.view.frame.size.width, height: 1)) self.navigationBar.shadowImage = shadowImg UIApplication.shared.statusBarStyle = .default }else{ let img = UIImage.getImageFromColor(color: UIColor.appColor(color: .Primary), size: CGSize(width: self.view.frame.size.width, height: 64)) self.navigationBar.setBackgroundImage(img, for: .default) let shadowImg = UIImage.getImageFromColor(color: UIColor.appColor(color: .PrimaryDark), size: CGSize(width: self.view.frame.size.width, height: 1)) self.navigationBar.shadowImage = shadowImg UIApplication.shared.statusBarStyle = .lightContent } } open override var preferredStatusBarStyle: UIStatusBarStyle{ if isTransparent{ return .default }else{ return .lightContent } } }
7196d5518d83d98792d8a4a39dae62ee
35.22449
159
0.660282
false
false
false
false
DragonCherry/CameraPreviewController
refs/heads/master
CameraPreviewController/Classes/CameraPreviewController+Filter.swift
mit
1
// // CameraPreviewController+Filter.swift // Pods // // Created by DragonCherry on 6/7/17. // // import UIKit import GPUImage // MARK: - Filter APIs extension CameraPreviewController { open func contains(targetFilter: GPUImageFilter?) -> Bool { guard let targetFilter = targetFilter else { return false } for filter in filters { if filter == targetFilter { return true } } return false } open func add(filter: GPUImageFilter?) { guard let filter = filter, !contains(targetFilter: filter) else { return } lastFilter.removeAllTargets() lastFilter.addTarget(filter) filter.addTarget(preview) if let videoWriter = self.videoWriter { filter.addTarget(videoWriter) } filters.append(filter) } open func add(newFilters: [GPUImageFilter]?) { guard let newFilters = newFilters, let firstNewFilter = newFilters.first, newFilters.count > 0 else { return } lastFilter.removeAllTargets() lastFilter.addTarget(firstNewFilter) filters.append(contentsOf: filters) if let videoWriter = self.videoWriter { filters.last?.addTarget(videoWriter) } filters.last?.addTarget(preview) } open func removeFilters() { defaultFilter.removeAllTargets() for filter in filters { filter.removeAllTargets() filter.removeFramebuffer() } filters.removeAll() if let videoWriter = self.videoWriter { defaultFilter.addTarget(videoWriter) } defaultFilter.addTarget(preview) } }
809342c540e4145b997ebf7a5b46cf18
27.728814
118
0.616519
false
false
false
false
ncvitak/TrumpBot
refs/heads/master
TrumpBotIntent/IntentHandler.swift
mit
1
// // IntentHandler.swift // TrumpBotIntent // // Created by Nico Cvitak on 2016-07-23. // Copyright © 2016 Nicholas Cvitak. All rights reserved. // import Intents import AVFoundation class IntentHandler: INExtension, INSendMessageIntentHandling, AVSpeechSynthesizerDelegate { let speechSynthesizer = AVSpeechSynthesizer() var contentResolveCompletion: ((INStringResolutionResult) -> Void)? override init() { try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [AVAudioSessionCategoryOptions.mixWithOthers]) try! AVAudioSession.sharedInstance().setActive(true) super.init() speechSynthesizer.delegate = self } override func handler(for intent: INIntent) -> AnyObject { // This is the default implementation. If you want different objects to handle different intents, // you can override this and return the handler you want for that particular intent. return self } func handle(sendMessage intent: INSendMessageIntent, completion: (INSendMessageIntentResponse) -> Swift.Void) { print("Message intent is being handled.") let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self)) let response = INSendMessageIntentResponse(code: .success, userActivity: userActivity) completion(response) } func resolveRecipients(forSendMessage intent: INSendMessageIntent, with completion: ([INPersonResolutionResult]) -> Void) { if let recipients = intent.recipients where recipients.count == 1 && recipients[0].displayName == "Donald" { completion([INPersonResolutionResult.success(with: recipients[0])]) } else { completion([INPersonResolutionResult.needsValue()]) } } func resolveContent(forSendMessage intent: INSendMessageIntent, with completion: (INStringResolutionResult) -> Void) { let content = intent.content != nil ? intent.content! : "" let response = botResponse(content: content.lowercased()) contentResolveCompletion = completion speechSynthesizer.speak(AVSpeechUtterance(string: response)) } func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { contentResolveCompletion?(INStringResolutionResult.needsValue()) contentResolveCompletion = nil } }
734ef73761f85c1eeb858c9638a8802d
40.387097
141
0.710055
false
false
false
false
neekon/ios
refs/heads/master
Neekon/Neekon/MainNavigationController.swift
mit
1
// // MainNavigationController.swift // Neekon // // Created by Eiman Zolfaghari on 2/9/15. // Copyright (c) 2015 Iranican Inc. All rights reserved. // import UIKit class MainNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() let bgImage = UIImage(named:"home-BG.jpg") let bgImageView = UIImageView(image: bgImage) bgImageView.frame = self.view.frame self.view.addSubview(bgImageView) self.view.sendSubviewToBack(bgImageView) self.view.backgroundColor = UIColor.clearColor() self.navigationBar.translucent = true self.navigationBar.barTintColor = UIColor.purpleColor() UITabBar.appearance().barTintColor = UIColor.purpleColor() UITabBar.appearance().tintColor = UIColor.whiteColor() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
fb30954939d6c83b1fd78e9161393910
28.352941
66
0.667335
false
false
false
false
GrandCentralBoard/GrandCentralBoard
refs/heads/develop
GrandCentralBoard/Widgets/GitHub/GitHubSource.swift
gpl-3.0
2
// // GitHubSource.swift // GrandCentralBoard // // Created by Michał Laskowski on 22/05/16. // import RxSwift import GCBCore struct GitHubSourceNoDataError: ErrorType, HavingMessage { let message = "GitHub returned no repositories".localized } private extension CollectionType where Generator.Element == Repository { func filterAndSortByPRCountAndName() -> [Repository] { return filter { $0.pullRequestsCount > 0 }.sort({ (left, right) -> Bool in if left.pullRequestsCount == right.pullRequestsCount { return left.name < right.name } return left.pullRequestsCount > right.pullRequestsCount }) } } final class GitHubSource: Asynchronous { typealias ResultType = Result<[Repository]> let sourceType: SourceType = .Momentary private let disposeBag = DisposeBag() private let dataProvider: GitHubDataProviding let interval: NSTimeInterval init(dataProvider: GitHubDataProviding, refreshInterval: NSTimeInterval) { self.dataProvider = dataProvider interval = refreshInterval } func read(closure: (ResultType) -> Void) { dataProvider.repositoriesWithPRsCount().single().map { (repositories) -> [Repository] in guard repositories.count > 0 else { throw GitHubSourceNoDataError() } return repositories.filterAndSortByPRCountAndName() }.observeOn(MainScheduler.instance).subscribe { (event) in switch event { case .Error(let error): closure(.Failure(error)) case .Next(let repositories): closure(.Success(repositories.filterAndSortByPRCountAndName())) case .Completed: break } }.addDisposableTo(disposeBag) } }
f88eabddf0e9b72d518aa099185c57d6
32.113208
105
0.676353
false
false
false
false
itouch2/LeetCode
refs/heads/master
LeetCode/SearchinRotatedSortedArray.swift
mit
1
// // SearchinRotatedSortedArray.swift // LeetCode // // Created by You Tu on 2017/9/11. // Copyright © 2017年 You Tu. All rights reserved. // import Cocoa /* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. */ class SearchinRotatedSortedArray: NSObject { func search(_ nums: [Int], _ target: Int) -> Int { return searchFromRange(nums, target, 0, nums.count - 1) } func searchFromRange(_ nums: [Int], _ target: Int, _ left: Int, _ right: Int) -> Int { if left > right { return -1 } let mid = left + (right - left) / 2 if nums[mid] == target { return mid } if nums[left] < nums[right] { if target < nums[left] { return -1 } if target > nums[right] { return -1 } return binarySearchFromRange(nums, target, left: left, right: right) } let leftIndex = searchFromRange(nums, target, mid + 1, right) if leftIndex != -1 { return leftIndex } return searchFromRange(nums, target, left, mid - 1) } func binarySearchFromRange(_ nums: [Int], _ target: Int, left: Int, right: Int) -> Int { if target < nums[left] || target > nums[right] { return -1 } if left > right { return -1 } let mid = left + (right - left) / 2 if nums[mid] == target { return mid } else if nums[mid] < target { return binarySearchFromRange(nums, target, left: mid + 1, right: right) } else { return binarySearchFromRange(nums, target, left: left, right: mid - 1) } } }
1349dabf9e282640b20ff33e50ad6d13
26.328947
101
0.519981
false
false
false
false
AlexIzh/Griddle
refs/heads/master
CollectionPresenter/3rd/DraggableCollectionViewFlowLayout.swift
mit
1
// // KDRearrangeableCollectionViewFlowLayout.swift // KDRearrangeableCollectionViewFlowLayout // // Created by Michael Michailidis on 16/03/2015. // Copyright (c) 2015 Karmadust. All rights reserved. // import UIKit @objc protocol DraggableCollectionViewFlowLayoutDelegate: UICollectionViewDelegate { func moveDataItem(_ fromIndexPath: IndexPath, toIndexPath: IndexPath) -> Void func didFinishMoving(_ fromIndexPath: IndexPath, toIndexPath: IndexPath) -> Void } class DraggableCollectionViewFlowLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate { var animating: Bool = false var collectionViewFrameInCanvas: CGRect = CGRect.zero var hitTestRectagles = [String: CGRect]() var startIndexPath: IndexPath? var canvas: UIView? { didSet { if canvas != nil { calculateBorders() } } } struct Bundle { var offset: CGPoint = CGPoint.zero var sourceCell: UICollectionViewCell var representationImageView: UIView var currentIndexPath: IndexPath } var bundle: Bundle? override init() { super.init() setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() setup() } func setup() { if let _ = self.collectionView { // let longPressGestureRecogniser = UILongPressGestureRecognizer(target: self, action: "handleGesture:") // // longPressGestureRecogniser.minimumPressDuration = 0.2 // longPressGestureRecogniser.delegate = self // // collectionView.addGestureRecognizer(longPressGestureRecogniser) if canvas == nil { canvas = collectionView!.superview } } } override func prepare() { super.prepare() calculateBorders() } fileprivate func calculateBorders() { if let collectionView = self.collectionView { collectionViewFrameInCanvas = collectionView.frame if canvas != collectionView.superview { collectionViewFrameInCanvas = canvas!.convert(collectionViewFrameInCanvas, from: collectionView) } var leftRect: CGRect = collectionViewFrameInCanvas leftRect.size.width = 20.0 hitTestRectagles["left"] = leftRect var topRect: CGRect = collectionViewFrameInCanvas topRect.size.height = 20.0 hitTestRectagles["top"] = topRect var rightRect: CGRect = collectionViewFrameInCanvas rightRect.origin.x = rightRect.size.width - 20.0 rightRect.size.width = 20.0 hitTestRectagles["right"] = rightRect var bottomRect: CGRect = collectionViewFrameInCanvas bottomRect.origin.y = bottomRect.origin.y + rightRect.size.height - 20.0 bottomRect.size.height = 20.0 hitTestRectagles["bottom"] = bottomRect } } // MARK: - UIGestureRecognizerDelegate func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if let ca = self.canvas { if let cv = self.collectionView { let pointPressedInCanvas = gestureRecognizer.location(in: ca) for cell in cv.visibleCells { let cellInCanvasFrame = ca.convert(cell.frame, from: cv) if cellInCanvasFrame.contains(pointPressedInCanvas) { let representationImage = cell.snapshotView(afterScreenUpdates: true) representationImage!.frame = cellInCanvasFrame let offset = CGPoint(x: pointPressedInCanvas.x - cellInCanvasFrame.origin.x, y: pointPressedInCanvas.y - cellInCanvasFrame.origin.y) let indexPath: IndexPath = cv.indexPath(for: cell as UICollectionViewCell)! bundle = Bundle(offset: offset, sourceCell: cell, representationImageView: representationImage!, currentIndexPath: indexPath) break } } } } return (bundle != nil) } func checkForDraggingAtTheEdgeAndAnimatePaging(_ gestureRecognizer: UILongPressGestureRecognizer) { if animating == true { return } if let bundle = self.bundle { _ = gestureRecognizer.location(in: canvas) var nextPageRect: CGRect = collectionView!.bounds if scrollDirection == UICollectionViewScrollDirection.horizontal { if bundle.representationImageView.frame.intersects(hitTestRectagles["left"]!) { nextPageRect.origin.x -= nextPageRect.size.width if nextPageRect.origin.x < 0.0 { nextPageRect.origin.x = 0.0 } } else if bundle.representationImageView.frame.intersects(hitTestRectagles["right"]!) { nextPageRect.origin.x += nextPageRect.size.width if nextPageRect.origin.x + nextPageRect.size.width > collectionView!.contentSize.width { nextPageRect.origin.x = collectionView!.contentSize.width - nextPageRect.size.width } } } else if scrollDirection == UICollectionViewScrollDirection.vertical { _ = hitTestRectagles["top"] if bundle.representationImageView.frame.intersects(hitTestRectagles["top"]!) { nextPageRect.origin.y -= nextPageRect.size.height if nextPageRect.origin.y < 0.0 { nextPageRect.origin.y = 0.0 } } else if bundle.representationImageView.frame.intersects(hitTestRectagles["bottom"]!) { nextPageRect.origin.y += nextPageRect.size.height if nextPageRect.origin.y + nextPageRect.size.height > collectionView!.contentSize.height { nextPageRect.origin.y = collectionView!.contentSize.height - nextPageRect.size.height } } } if !nextPageRect.equalTo(collectionView!.bounds) { let delayTime = DispatchTime.now() + Double(Int64(0.8 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime, execute: { self.animating = false self.handleGesture(gestureRecognizer) }) animating = true collectionView!.scrollRectToVisible(nextPageRect, animated: true) } } } func handleGesture(_ gesture: UILongPressGestureRecognizer) { if let bundle = self.bundle { let dragPointOnCanvas = gesture.location(in: canvas) if gesture.state == UIGestureRecognizerState.began { bundle.sourceCell.isHidden = true canvas?.addSubview(bundle.representationImageView) // UIView.animateWithDuration(0.5, animations: { () -> Void in // bundle.representationImageView.alpha = 0.8 // }); let dragPointOnCollectionView = gesture.location(in: collectionView) startIndexPath = collectionView?.indexPathForItem(at: dragPointOnCollectionView) } if gesture.state == UIGestureRecognizerState.changed { // Update the representation image var imageViewFrame = bundle.representationImageView.frame var point = CGPoint.zero point.x = dragPointOnCanvas.x - bundle.offset.x point.y = dragPointOnCanvas.y - bundle.offset.y imageViewFrame.origin = point bundle.representationImageView.frame = imageViewFrame let dragPointOnCollectionView = gesture.location(in: collectionView) if let indexPath: IndexPath = self.collectionView?.indexPathForItem(at: dragPointOnCollectionView) { checkForDraggingAtTheEdgeAndAnimatePaging(gesture) if (indexPath == bundle.currentIndexPath) == false { // If we have a collection view controller that implements the delegate we call the method first if let delegate = self.collectionView!.delegate as? DraggableCollectionViewFlowLayoutDelegate { delegate.moveDataItem(bundle.currentIndexPath, toIndexPath: indexPath) } collectionView!.moveItem(at: bundle.currentIndexPath, to: indexPath) self.bundle!.currentIndexPath = indexPath } } } if gesture.state == UIGestureRecognizerState.ended { bundle.sourceCell.isHidden = false bundle.representationImageView.removeFromSuperview() if let _ = self.collectionView?.delegate as? DraggableCollectionViewFlowLayoutDelegate { // if we have a proper data source then we can reload and have the data displayed correctly collectionView!.reloadData() } if let delegate = self.collectionView!.delegate as? DraggableCollectionViewFlowLayoutDelegate { if let start = self.startIndexPath { delegate.didFinishMoving(start, toIndexPath: self.bundle!.currentIndexPath) } } self.bundle = nil } } } }
73dd684bae235c6d1c1d6ca7133530aa
31.71831
192
0.630865
false
false
false
false
STShenZhaoliang/STKitSwift
refs/heads/master
STKitSwift/Date+STKit.swift
mit
1
// // Date+STKit.swift // STKitSwift // // The MIT License (MIT) // // Copyright (c) 2019 沈天 // // 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 /// This extension add some useful functions to Date. public extension Date { // MARK: - Variables /// Set and get current year. var year: Int { get { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.year], from: self) guard let year = components.year else { return 0 } return year } set { update(components: [.year: newValue]) } } /// Set and get current month. var month: Int { get { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.month], from: self) guard let month = components.month else { return 0 } return month } set { update(components: [.month: newValue]) } } /// Set and get current day. var day: Int { get { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.day], from: self) guard let day = components.day else { return 0 } return day } set { update(components: [.day: newValue]) } } /// Set and get current hour. var hour: Int { get { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.hour], from: self) guard let hour = components.hour else { return 0 } return hour } set { update(components: [.hour: newValue]) } } /// Set and get current minute. var minute: Int { get { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.minute], from: self) guard let minute = components.minute else { return 0 } return minute } set { update(components: [.minute: newValue]) } } /// Set and get current second. var second: Int { get { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.second], from: self) guard let second = components.second else { return 0 } return second } set { update(components: [.second: newValue]) } } /// Get current nanosecond. var nanosecond: Int { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.nanosecond], from: self) guard let nanosecond = components.nanosecond else { return 0 } return nanosecond } /// Get the weekday number from /// - 1 - Sunday. /// - 2 - Monday. /// - 3 - Tuerday. /// - 4 - Wednesday. /// - 5 - Thursday. /// - 6 - Friday. /// - 7 - Saturday. var weekday: Int { let calendar = Calendar.autoupdatingCurrent let components = calendar.dateComponents([.weekday], from: self) guard let weekday = components.weekday else { return 0 } return weekday } /// Editable date components. /// /// - year: Year component. /// - month: Month component. /// - day: Day component. /// - hour: Hour component. /// - minute: Minute component. /// - second: Second component. enum EditableDateComponents: Int { case year case month case day case hour case minute case second } // MARK: - Functions /// Update current Date components. /// /// - Parameters: /// - components: Dictionary of components and values to be updated. mutating func update(components: [EditableDateComponents: Int]) { let autoupdatingCalendar = Calendar.autoupdatingCurrent var dateComponents = autoupdatingCalendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second, .nanosecond], from: self) for (component, value) in components { switch component { case .year: dateComponents.year = value case .month: dateComponents.month = value case .day: dateComponents.day = value case .hour: dateComponents.hour = value case .minute: dateComponents.minute = value case .second: dateComponents.second = value } } let calendar = Calendar(identifier: autoupdatingCalendar.identifier) guard let date = calendar.date(from: dateComponents) else { return } self = date } }
5bfd7979e6246f5f72c4dcf04d9371eb
28.704225
147
0.549708
false
false
false
false
hujewelz/hotaru
refs/heads/master
Hotaru/Classes/Core/Cancelable.swift
mit
1
// // Cancelable.swift // Hotaru // // Created by huluobo on 2017/12/25. // import Foundation public protocol Cancelable { var isCanceled: Bool { get set } mutating func cancel() /// Add a Cancelabel to the default Cancel bag func addToCancelBag() /// Add a Cancelabel to Cancel bag func addTo(_ cancelBag: CancelBag) } public extension Cancelable { public mutating func cancel() { isCanceled = true } public func addToCancelBag() {} public func addTo(_ cancelBag: CancelBag) { cancelBag.addToCancelBag(self) } } public protocol CancelBag: class { func addToCancelBag(_ cancelable: Cancelable) } final class Cancel { typealias Canceled = () -> Void var isCanceled: Bool = false fileprivate weak var obj: CancelBag? fileprivate var canceled: Canceled static func create(obj: CancelBag? = nil, _ canceled: @escaping Canceled) -> Cancel { return Cancel(obj: obj, canceled) } init(obj: CancelBag? = nil, _ canceled: @escaping Canceled) { self.obj = obj self.canceled = canceled } deinit { canceled() } } extension Cancel: Cancelable { func addToCancelBag() { obj?.addToCancelBag(self) } func cancel() { isCanceled = true canceled() } }
9dad41f0d252d3b70cdfeada9b0a588d
17.837838
89
0.598996
false
false
false
false
SheepYo/HAYO
refs/heads/master
iOS/HAYO/FriendView.swift
mit
1
// // FriendView.swift // Sheep // // Created by mono on 8/3/14. // Copyright (c) 2014 Sheep. All rights reserved. // import Foundation class FriendView: UIView { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nicknameLabel: UILabel! class func create() -> FriendView { return NSBundle.mainBundle().loadNibNamed("FriendView", owner: self, options: nil)[0] as FriendView } override func awakeFromNib() { super.awakeFromNib() imageView.configureAsMyCircle() self.layer.borderColor = UIColor.whiteColor().CGColor self.layer.borderWidth = 2 self.layer.cornerRadius = 4 } var _user: User! var user: User! { get { return _user } set { _user = newValue nicknameLabel.text = _user.username if let image = _user.image { imageView.image = image return } imageView.sd_setImageWithURL(NSURL(string: _user.imageURL), completed: {image, error, type, url -> () in }) } } }
d6cb93d0ca30589f324ec00cab75f9ef
23.108696
112
0.57852
false
false
false
false
myriadmobile/Droar
refs/heads/master
Droar/Classes/Droar Core/Droar.swift
mit
1
// // Droar.swift // Pods // // Created by Nathan Jangula on 6/5/17. // // import UIKit @objc public enum DroarGestureType: UInt { case tripleTap, panFromRight } @objc public class Droar: NSObject { // Droar is a purely static class. private override init() { } static var window: DroarWindow! internal static var navController: UINavigationController! internal static var viewController: DroarViewController? internal static let drawerWidth: CGFloat = 300 private static let startOnce = DispatchOnce() public static private(set) var isStarted = false; @objc public static func start() { startOnce.perform { initializeWindow() setGestureType(.panFromRight) KnobManager.sharedInstance.prepareForStart() Droar.isStarted = true } } @objc public static func setGestureType(_ type: DroarGestureType, _ threshold: CGFloat = 50.0) { configureRecognizerForType(type, threshold) } //Navigation @objc public static func pushViewController(_ viewController: UIViewController, animated: Bool) { navController.pushViewController(viewController, animated: animated) } @objc public static func present(_ viewController: UIViewController, animated: Bool, completion: (() -> Void)?) { navController.present(viewController, animated: animated, completion: completion) } //Internal Accessors static func loadKeyWindow() -> UIWindow? { var window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first if window == nil { window = UIApplication.shared.keyWindow } return window } static func loadActiveResponder() -> UIViewController? { return loadKeyWindow()?.rootViewController } } //Knobs extension Droar { @objc public static func register(_ knob: DroarKnob) { KnobManager.sharedInstance.registerStaticKnob(knob) viewController?.tableView.reloadData() } @objc(registerDefaultKnobs:) public static func objc_registerDefaultKnobs(knobs: [Int]) { registerDefaultKnobs(knobs.map({ DefaultKnobType(rawValue: $0)! })) } public static func registerDefaultKnobs(_ knobs: [DefaultKnobType]) { KnobManager.sharedInstance.registerDefaultKnobs(knobs) viewController?.tableView.reloadData() } public static func refreshKnobs() { viewController?.tableView.reloadData() } } //Visibility extension Droar { //Technically this could be wrong depending on the tx value, but it is close enough. @objc public static var isVisible: Bool { return !(navController.view.transform == CGAffineTransform.identity) } @objc public static func openDroar(completion: (()->Void)? = nil) { window.isHidden = false UIView.animate(withDuration: 0.25, animations: { navController.view.transform = CGAffineTransform(translationX: -navController.view.frame.size.width, y: 0) window.setActivationPercent(1) }) { (completed) in //Swap gestures openRecognizer.view?.removeGestureRecognizer(openRecognizer) window.addGestureRecognizer(dismissalRecognizer) completion?() } } @objc public static func closeDroar(completion: (()->Void)? = nil) { UIView.animate(withDuration: 0.25, animations: { navController.view.transform = CGAffineTransform.identity window.setActivationPercent(0) }) { (completed) in window.isHidden = true //Swap gestures dismissalRecognizer.view?.removeGestureRecognizer(dismissalRecognizer) replaceGestureRecognizer(with: openRecognizer) completion?() } } @objc static func toggleVisibility(completion: (()->Void)? = nil) { if isVisible { closeDroar(completion: completion) } else { openDroar(completion: completion) } } } //Backwards compatibility extension Droar { public static func dismissWindow() { closeDroar(completion: nil) } }
54a39ceca5c13326bba8c5494e2a8ff1
28.9375
118
0.638367
false
false
false
false
larryhou/swift
refs/heads/master
Tachograph/Tachograph/RouteBrowerController.swift
mit
1
// // BrowserViewController.swift // Tachograph // // Created by larryhou on 4/7/2017. // Copyright © 2017 larryhou. All rights reserved. // import Foundation import AVFoundation import UIKit import AVKit class AssetCell: UITableViewCell { @IBOutlet weak var ib_image: UIImageView! @IBOutlet weak var ib_time: UILabel! @IBOutlet weak var ib_progress: UIProgressView! @IBOutlet weak var ib_id: UILabel! @IBOutlet weak var ib_share: UIButton! @IBOutlet weak var ib_download: UIButton! var data: CameraModel.CameraAsset? func progressUpdate(name: String, value: Float) { if value < 1.0 || Float.nan == value { ib_share.isHidden = true } else { ib_share.isHidden = false } ib_progress.progress = value ib_download.isHidden = !ib_share.isHidden ib_progress.isHidden = ib_download.isHidden } } class EventBrowserController: RouteBrowerController { override func viewDidLoad() { super.viewDidLoad() assetType = .event } override func loadModel() { loading = true CameraModel.shared.fetchEventVideos() } } class RouteBrowerController: UIViewController, UITableViewDelegate, UITableViewDataSource, CameraModelDelegate, AssetManagerDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var movieView: UIView! var videoAssets: [CameraModel.CameraAsset] = [] var formatter: DateFormatter! var loadingIndicator: UIActivityIndicatorView! var playController: AVPlayerViewController! var assetType: CameraModel.AssetType = .route override func viewDidLoad() { super.viewDidLoad() formatter = DateFormatter() formatter.dateFormat = "HH:mm/MM-dd" loadViews() } override func viewWillAppear(_ animated: Bool) { loadModel() CameraModel.shared.delegate = self AssetManager.shared.delegate = self } func loadModel() { loading = true CameraModel.shared.fetchRouteVideos() } func loadViews() { loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) loadingIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50) loadingIndicator.hidesWhenStopped = false playController = AVPlayerViewController() playController.entersFullScreenWhenPlaybackBegins = true playController.view.frame = CGRect(origin: CGPoint(), size: movieView.frame.size) movieView.addSubview(playController.view) } func assetManager(_ manager: AssetManager, progress: Float, of name: String) { for cell in tableView.visibleCells { if let assetCell = cell as? AssetCell, let data = assetCell.data, data.name == name { let progress = AssetManager.shared.get(progressOf: name) assetCell.progressUpdate(name: name, value: progress) break } } } func model(update: CameraModel.CameraAsset, type: CameraModel.AssetType) { if type != assetType {return} videoAssets.insert(update, at: 0) let index = IndexPath(row: 0, section: 0) tableView.insertRows(at: [index], with: UITableViewRowAnimation.top) } func model(assets: [CameraModel.CameraAsset], type: CameraModel.AssetType) { if self.videoAssets.count != assets.count { loading = false videoAssets = assets guard let tableView = self.tableView else {return} tableView.reloadData() } guard let tableView = self.tableView else {return} loadingIndicator.stopAnimating() tableView.tableFooterView = nil } // MARK: cell @IBAction func share(_ sender: UIButton) { let rect = sender.superview!.convert(sender.frame, to: tableView) if let list = tableView.indexPathsForRows(in: rect) { let data = videoAssets[list[0].row] if let location = AssetManager.shared.get(cacheOf: data.url) { let controller = UIActivityViewController(activityItems: [location], applicationActivities: nil) present(controller, animated: true, completion: nil) } } } @IBAction func download(_ sender: UIButton) { let rect = sender.superview!.convert(sender.frame, to: tableView) if let list = tableView.indexPathsForRows(in: rect) { let data = videoAssets[list[0].row] AssetManager.shared.load(url: data.url, completion: nil, progression: nil) } } // MARK: table func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return videoAssets.count } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == videoAssets.count - 1 { if tableView.tableFooterView == nil { tableView.tableFooterView = loadingIndicator } loadingIndicator.startAnimating() loadModel() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let data = videoAssets[indexPath.row] guard let url = URL(string: data.url) else {return} if playController.player == nil { playController.player = AVPlayer(url: url) } else { playController.player?.replaceCurrentItem(with: AVPlayerItem(url: url)) } playController.player?.play() } var loading = false func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "AssetCell") as? AssetCell { let data = videoAssets[indexPath.row] cell.ib_time.text = formatter.string(from: data.timestamp) cell.ib_progress.isHidden = true cell.ib_progress.progress = 0.0 cell.ib_id.text = data.id cell.data = data if let url = AssetManager.shared.get(cacheOf: data.icon) { cell.ib_image.image = try! UIImage(data: Data(contentsOf: url)) } else { cell.ib_image.image = UIImage(named: "icon.thm") AssetManager.shared.load(url: data.icon, completion: { cell.ib_image.image = UIImage(data: $1) }) } cell.ib_share.isHidden = !AssetManager.shared.has(cacheOf: data.url) cell.ib_download.isHidden = !cell.ib_share.isHidden return cell } return UITableViewCell() } override var supportedInterfaceOrientations: UIInterfaceOrientationMask {return .portrait} }
bf186054a23fd6b136b5bb1e3e3c365b
32.816425
112
0.637143
false
false
false
false
mobilabsolutions/jenkins-ios
refs/heads/master
JenkinsiOS/Controller/SettingsTableViewController.swift
mit
1
// // SettingsTableViewController.swift // JenkinsiOS // // Created by Robert on 07.08.18. // Copyright © 2018 MobiLab Solutions. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController, AccountProvidable, CurrentAccountProviding, CurrentAccountProvidingDelegate { var account: Account? { didSet { guard let account = account else { return } updateSections(for: account) tableView.reloadData() } } private let remoteConfigManager = RemoteConfigurationManager() private var shouldUseDirectAccountDesign: Bool { return remoteConfigManager.configuration.shouldUseNewAccountDesign } var currentAccountDelegate: CurrentAccountProvidingDelegate? @IBOutlet var versionLabel: UILabel! private enum SettingsSection { case plugins case users case accounts(currentAccountName: String) case currentAccount(currentAccountName: String) case otherAccounts(otherAccountNames: [String]) case about struct Cell { enum CellType { case contentCell case creationCell } let actionTitle: String let type: CellType } var title: String { switch self { case .plugins: return "PLUGINS" case .users: return "USERS" case .accounts(currentAccountName: _): return "ACCOUNTS" case .currentAccount(currentAccountName: _): return "ACTIVE ACCOUNT" case .otherAccounts(otherAccountNames: _): return "OTHER ACCOUNTS" case .about: return "INFO" } } var cells: [Cell] { switch self { case .plugins: return [Cell(actionTitle: "View Plugins", type: .contentCell)] case .users: return [Cell(actionTitle: "View Users", type: .contentCell)] case let .accounts(currentAccountName): return [Cell(actionTitle: currentAccountName, type: .contentCell)] case let .currentAccount(currentAccountName): return [Cell(actionTitle: currentAccountName, type: .contentCell)] case let .otherAccounts(otherAccountNames): return otherAccountNames.map { Cell(actionTitle: $0, type: .contentCell) } + [Cell(actionTitle: "Add account", type: .creationCell)] case .about: return [Cell(actionTitle: "About Butler", type: .contentCell), Cell(actionTitle: "FAQs", type: .contentCell)] } } } private var sections: [SettingsSection] = [] override func viewDidLoad() { super.viewDidLoad() tabBarController?.navigationItem.title = "Settings" tableView.backgroundColor = Constants.UI.backgroundColor tableView.separatorStyle = .none tableView.register(UINib(nibName: "CreationTableViewCell", bundle: .main), forCellReuseIdentifier: Constants.Identifiers.creationCell) setBottomContentInsetForOlderDevices() setVersionNumberText() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.navigationItem.title = "Settings" tableView.reloadData() // Make sure the navigation item does not contain the search bar. if #available(iOS 11.0, *) { tabBarController?.navigationItem.searchController = nil } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) LoggingManager.loggingManager.logSettingsView(accountsIncluded: shouldUseDirectAccountDesign) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() resizeFooter() } // MARK: - Table view data source override func numberOfSections(in _: UITableView) -> Int { return sections.count } override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 + sections[section].cells.count } override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return 47 } return 42 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.headerCell, for: indexPath) cell.textLabel?.text = sections[indexPath.section].title cell.selectionStyle = .none cell.contentView.backgroundColor = Constants.UI.backgroundColor cell.textLabel?.backgroundColor = Constants.UI.backgroundColor cell.textLabel?.textColor = Constants.UI.skyBlue cell.textLabel?.font = UIFont.boldDefaultFont(ofSize: 13) return cell } else if sections[indexPath.section].cells[indexPath.row - 1].type == .creationCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.creationCell, for: indexPath) as! CreationTableViewCell cell.contentView.backgroundColor = .white cell.titleLabel.text = sections[indexPath.section].cells[indexPath.row - 1].actionTitle return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.settingsCell, for: indexPath) as! BasicTableViewCell cell.contentView.backgroundColor = .white cell.title = sections[indexPath.section].cells[indexPath.row - 1].actionTitle return cell } } override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.row != 0 else { return } if sections[indexPath.section].cells[indexPath.row - 1].type == .creationCell { performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: sections[indexPath.section].cells[indexPath.row - 1]) return } switch sections[indexPath.section] { case .plugins: performSegue(withIdentifier: Constants.Identifiers.showPluginsSegue, sender: nil) case .users: performSegue(withIdentifier: Constants.Identifiers.showUsersSegue, sender: nil) case .accounts: performSegue(withIdentifier: Constants.Identifiers.showAccountsSegue, sender: nil) case .currentAccount: performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: account) case .otherAccounts: guard let current = account else { return } let nonCurrent = nonCurrentAccounts(currentAccount: current) performSegue(withIdentifier: Constants.Identifiers.editAccountSegue, sender: nonCurrent[indexPath.row - 1]) case .about: if indexPath.row == 1 { performSegue(withIdentifier: Constants.Identifiers.aboutSegue, sender: nil) } else if indexPath.row == 2 { performSegue(withIdentifier: Constants.Identifiers.faqSegue, sender: nil) } } } func didChangeCurrentAccount(current: Account) { currentAccountDelegate?.didChangeCurrentAccount(current: current) account = current tableView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let providedAccount = sender as? Account, var dest = segue.destination as? AccountProvidable { dest.account = providedAccount } else if let cell = sender as? SettingsSection.Cell, cell.type == .creationCell, var dest = segue.destination as? AccountProvidable { dest.account = nil } else if var dest = segue.destination as? AccountProvidable { dest.account = account } if var dest = segue.destination as? CurrentAccountProviding { dest.currentAccountDelegate = self } if let dest = segue.destination as? AccountDeletionNotifying { dest.accountDeletionDelegate = tabBarController as? AccountDeletionNotified } if let dest = segue.destination as? AddAccountContainerViewController { dest.delegate = self } if let dest = segue.destination as? AddAccountContainerViewController, let account = sender as? Account { dest.editingCurrentAccount = account == self.account } } private func updateSections(for account: Account) { if shouldUseDirectAccountDesign { sections = [ .plugins, .users, .currentAccount(currentAccountName: account.displayName ?? account.baseUrl.absoluteString), .otherAccounts(otherAccountNames: nonCurrentAccounts(currentAccount: account).map { $0.displayName ?? $0.baseUrl.absoluteString }), .about, ] } else { sections = [ .plugins, .users, .accounts(currentAccountName: account.displayName ?? account.baseUrl.absoluteString), .about, ] } } private func nonCurrentAccounts(currentAccount account: Account) -> [Account] { return AccountManager.manager.accounts.filter { !$0.isEqual(account) }.sorted(by: { (first, second) -> Bool in (first.displayName ?? first.baseUrl.absoluteString) < (second.displayName ?? second.baseUrl.absoluteString) }) } private func setVersionNumberText() { let provider = VersionNumberBuilder() versionLabel.text = provider.fullVersionNumberDescription } private func resizeFooter() { guard let footer = tableView.tableFooterView else { return } let tabBarHeight = tabBarController?.tabBar.frame.height ?? 0 let navigationBarHeight = navigationController?.navigationBar.frame.height ?? 0 let statusBarHeight = UIApplication.shared.statusBarFrame.height let additionalHeight = tabBarHeight + navigationBarHeight + statusBarHeight let newMinimumHeight = tableView.frame.height - tableView.visibleCells.reduce(0, { $0 + $1.bounds.height }) - additionalHeight footer.frame = CGRect(x: footer.frame.minX, y: footer.frame.minY, width: footer.frame.width, height: max(20, newMinimumHeight)) } } extension SettingsTableViewController: AddAccountTableViewControllerDelegate { func didEditAccount(account: Account, oldAccount: Account?, useAsCurrentAccount: Bool) { if useAsCurrentAccount { self.account = account currentAccountDelegate?.didChangeCurrentAccount(current: account) } var shouldAnimateNavigationStackChanges = true if oldAccount == nil { let confirmationController = AccountCreatedViewController(nibName: "AccountCreatedViewController", bundle: .main) confirmationController.delegate = self navigationController?.pushViewController(confirmationController, animated: true) shouldAnimateNavigationStackChanges = false } var viewControllers = navigationController?.viewControllers ?? [] // Remove the add account view controller from the navigation controller stack viewControllers = viewControllers.filter { !($0 is AddAccountContainerViewController) } navigationController?.setViewControllers(viewControllers, animated: shouldAnimateNavigationStackChanges) if let currentAccount = self.account { updateSections(for: currentAccount) } tableView.reloadData() } func didDeleteAccount(account: Account) { if account == self.account { self.account = AccountManager.manager.accounts.first } if let currentAccount = self.account { updateSections(for: currentAccount) } tableView.reloadData() navigationController?.popViewController(animated: false) let handler = OnBoardingHandler() if AccountManager.manager.accounts.isEmpty, handler.shouldShowAccountCreationViewController() { let navigationController = UINavigationController() present(navigationController, animated: false, completion: nil) handler.showAccountCreationViewController(on: navigationController, delegate: self) } } } extension SettingsTableViewController: AccountCreatedViewControllerDelegate { func doneButtonPressed() { navigationController?.popViewController(animated: true) } } extension SettingsTableViewController: OnBoardingDelegate { func didFinishOnboarding(didAddAccount _: Bool) { account = AccountManager.manager.currentAccount ?? AccountManager.manager.accounts.first dismiss(animated: true, completion: nil) } }
89b91ab4e134be711bed6dadfbc76e58
39.387692
147
0.655036
false
false
false
false
4jchc/4jchc-BaiSiBuDeJie
refs/heads/master
4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Essence-精华/View/XMGCommentCell.swift
apache-2.0
1
// // XMGCommentCell.swift // 4jchc-BaiSiBuDeJie // // Created by 蒋进 on 16/3/1. // Copyright © 2016年 蒋进. All rights reserved. // import UIKit protocol TableViewCellDelegate { func tableCellSelected( var tableCell : UITableViewCell) } class XMGCommentCell: UITableViewCell { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var sexView: UIImageView! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var likeCountLabel: UILabel! @IBOutlet weak var voiceButton: UIButton! var delegate : TableViewCellDelegate? override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if((self.delegate) != nil) { delegate?.tableCellSelected(self); } // Configure the view for the selected state } /// 让label有资格成为第一响应者 override func canBecomeFirstResponder() -> Bool { return true } /** * label能执行哪些操作(比如copy, paste等等) * @return YES:支持这种操作 */ override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { //super.canPerformAction(action, withSender: sender) return false } override func awakeFromNib() { super.awakeFromNib() // Initialization code self.backgroundView = UIImageView(image: UIImage(named: "mainCellBackground")) // self.profileImageView.layer.cornerRadius = self.profileImageView.width * 0.5; // self.profileImageView.layer.masksToBounds = true } /** 评论 */ var comment:XMGComment?{ didSet{ //self.profileImageView.sd_setImageWithURL(NSURL(string: comment!.user!.profile_image!), placeholderImage: UIImage(named: "defaultUserIcon")) self.profileImageView.setHeader(comment!.user!.profile_image!) self.sexView.image = comment!.user!.sex?.isEqualToString(XMGUserSexMale) == true ? UIImage(named: "Profile_manIcon") : UIImage(named: "Profile_womanIcon") self.contentLabel.text = comment!.content; self.usernameLabel.text = comment!.user!.username; self.likeCountLabel.text = String(format: "%zd",comment!.like_count) if (comment!.voiceuri!.length > 0) { self.voiceButton.hidden = false self.voiceButton.setTitle("\(comment!.voicetime)''", forState: .Normal) } else { self.voiceButton.hidden = true } } } /* //MARK: 重写frame来设置cell的内嵌 override var frame:CGRect{ set{ var frame = newValue frame.origin.x = XMGTopicCellMargin; frame.size.width -= 2 * XMGTopicCellMargin; super.frame=frame } get{ return super.frame } } */ }
407f92f9677ed2a99287300613053c8e
26.896226
166
0.611769
false
false
false
false
antlr/antlr4
refs/heads/dev
runtime/Swift/Sources/Antlr4/RuleContext.swift
bsd-3-clause
4
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// A rule context is a record of a single rule invocation. /// /// We form a stack of these context objects using the parent /// pointer. A parent pointer of null indicates that the current /// context is the bottom of the stack. The ParserRuleContext subclass /// as a children list so that we can turn this data structure into a /// tree. /// /// The root node always has a null pointer and invokingState of ATNState.INVALID_STATE_NUMBER. /// /// Upon entry to parsing, the first invoked rule function creates a /// context object (asubclass specialized for that rule such as /// SContext) and makes it the root of a parse tree, recorded by field /// Parser._ctx. /// /// public final SContext s() throws RecognitionException { /// SContext _localctx = new SContext(_ctx, getState()); <-- create new node /// enterRule(_localctx, 0, RULE_s); <-- push it /// ... /// exitRule(); <-- pop back to _localctx /// return _localctx; /// } /// /// A subsequent rule invocation of r from the start rule s pushes a /// new context object for r whose parent points at s and use invoking /// state is the state with r emanating as edge label. /// /// The invokingState fields from a context object to the root /// together form a stack of rule indication states where the root /// (bottom of the stack) has a -1 sentinel value. If we invoke start /// symbol s then call r1, which calls r2, the would look like /// this: /// /// SContext[-1] <- root node (bottom of the stack) /// R1Context[p] <- p in rule s called r1 /// R2Context[q] <- q in rule r1 called r2 /// /// So the top of the stack, _ctx, represents a call to the current /// rule and it holds the return address from another rule that invoke /// to this rule. To invoke a rule, we must always have a current context. /// /// The parent contexts are useful for computing lookahead sets and /// getting error information. /// /// These objects are used during parsing and prediction. /// For the special case of parsers, we use the subclass /// ParserRuleContext. /// /// - SeeAlso: org.antlr.v4.runtime.ParserRuleContext /// open class RuleContext: RuleNode { /// What context invoked this rule? public weak var parent: RuleContext? /// What state invoked the rule associated with this context? /// The "return address" is the followState of invokingState /// If parent is null, this should be ATNState.INVALID_STATE_NUMBER /// this context object represents the start rule. /// public var invokingState = ATNState.INVALID_STATE_NUMBER public init() { } public init(_ parent: RuleContext?, _ invokingState: Int) { self.parent = parent //if ( parent!=null ) { print("invoke "+stateNumber+" from "+parent)} self.invokingState = invokingState } open func depth() -> Int { var n = 0 var p: RuleContext? = self while let pWrap = p { p = pWrap.parent n += 1 } return n } /// A context is empty if there is no invoking state; meaning nobody called /// current context. /// open func isEmpty() -> Bool { return invokingState == ATNState.INVALID_STATE_NUMBER } // satisfy the ParseTree / SyntaxTree interface open func getSourceInterval() -> Interval { return Interval.INVALID } open func getRuleContext() -> RuleContext { return self } open func getParent() -> Tree? { return parent } open func setParent(_ parent: RuleContext) { self.parent = parent } open func getPayload() -> AnyObject { return self } /// Return the combined text of all child nodes. This method only considers /// tokens which have been added to the parse tree. /// /// Since tokens on hidden channels (e.g. whitespace or comments) are not /// added to the parse trees, they will not appear in the output of this /// method. /// open func getText() -> String { let length = getChildCount() if length == 0 { return "" } var builder = "" for i in 0..<length { builder += self[i].getText() } return builder } open func getRuleIndex() -> Int { return -1 } open func getAltNumber() -> Int { return ATN.INVALID_ALT_NUMBER } open func setAltNumber(_ altNumber: Int) { } open func getChild(_ i: Int) -> Tree? { return nil } open func getChildCount() -> Int { return 0 } open subscript(index: Int) -> ParseTree { preconditionFailure("Index out of range (RuleContext never has children, though its subclasses may).") } open func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? { return visitor.visitChildren(self) } /// Print out a whole tree, not just a node, in LISP format /// (root child1 .. childN). Print just a node if this is a leaf. /// We have to know the recognizer so we can get rule names. /// open func toStringTree(_ recog: Parser) -> String { return Trees.toStringTree(self, recog) } /// Print out a whole tree, not just a node, in LISP format /// (root child1 .. childN). Print just a node if this is a leaf. /// public func toStringTree(_ ruleNames: [String]?) -> String { return Trees.toStringTree(self, ruleNames) } open func toStringTree() -> String { return toStringTree(nil) } open var description: String { return toString(nil, nil) } open var debugDescription: String { return description } public final func toString<T>(_ recog: Recognizer<T>) -> String { return toString(recog, ParserRuleContext.EMPTY) } public final func toString(_ ruleNames: [String]) -> String { return toString(ruleNames, nil) } // recog null unless ParserRuleContext, in which case we use subclass toString(...) open func toString<T>(_ recog: Recognizer<T>?, _ stop: RuleContext) -> String { let ruleNames = recog?.getRuleNames() return toString(ruleNames, stop) } open func toString(_ ruleNames: [String]?, _ stop: RuleContext?) -> String { var buf = "" var p: RuleContext? = self buf += "[" while let pWrap = p, pWrap !== stop { if let ruleNames = ruleNames { let ruleIndex = pWrap.getRuleIndex() let ruleIndexInRange = (ruleIndex >= 0 && ruleIndex < ruleNames.count) let ruleName = (ruleIndexInRange ? ruleNames[ruleIndex] : String(ruleIndex)) buf += ruleName } else { if !pWrap.isEmpty() { buf += String(pWrap.invokingState) } } if let pWp = pWrap.parent, (ruleNames != nil || !pWp.isEmpty()) { buf += " " } p = pWrap.parent } buf += "]" return buf } open func castdown<T>(_ subType: T.Type) -> T { return self as! T } }
b2f8d05afdd09a7567bcce411a6c6e4d
29.932773
110
0.609209
false
false
false
false
avito-tech/Marshroute
refs/heads/master
Marshroute/Sources/Routers/BaseImpls/BaseRouter/BaseRouter.swift
mit
1
import UIKit /// Роутер, управляющий одним экраном (одним UINavigationController'ом) /// Работает с одим обработчиком переходов (detail). /// Например, роутер обычного экрана iPhone-приложения или роутер экрана внутри UIPopoverController'а open class BaseRouter: TransitionsHandlersProviderHolder, TransitionIdGeneratorHolder, RouterIdentifiable, RouterPresentable, RouterTransitionable, ModalPresentationRouter, PopoverPresentationRouter, EndpointRouter, RouterFocusable, RouterDismissable, DetailRouterTransitionable, DetailRouter, RouterControllersProviderHolder { public let transitionsHandlerBox: RouterTransitionsHandlerBox public let transitionId: TransitionId open fileprivate(set) weak var presentingTransitionsHandler: TransitionsHandler? public let transitionsHandlersProvider: TransitionsHandlersProvider public let transitionIdGenerator: TransitionIdGenerator public let controllersProvider: RouterControllersProvider public init(routerSeed seed: RouterSeed) { self.transitionId = seed.transitionId self.transitionsHandlerBox = seed.transitionsHandlerBox self.presentingTransitionsHandler = seed.presentingTransitionsHandler self.transitionsHandlersProvider = seed.transitionsHandlersProvider self.transitionIdGenerator = seed.transitionIdGenerator self.controllersProvider = seed.controllersProvider } // MARK: - DetailRouterTransitionable open var detailTransitionsHandlerBox: RouterTransitionsHandlerBox { return transitionsHandlerBox } }
78285b184883f6918b41bfc43be1f562
37.52381
101
0.78801
false
false
false
false
NachoSoto/AsyncImageView
refs/heads/master
AsyncImageView/Renderers/RemoteOrLocalImageRenderer.swift
mit
1
// // RemoteOrLocalImageRenderer.swift // AsyncImageView // // Created by Nacho Soto on 2/17/17. // Copyright © 2017 Nacho Soto. All rights reserved. // import UIKit import ReactiveSwift public enum RemoteOrLocalRenderData<Local: LocalRenderDataType, Remote: RemoteRenderDataType>: RenderDataType { case local(Local) case remote(Remote) } /// `RendererType` which downloads images and/or loads images from the bundle. /// /// - seealso: RemoteImageRenderer /// - seealso: LocalImageRenderer public final class RemoteOrLocalImageRenderer<Local: LocalRenderDataType, Remote: RemoteRenderDataType>: RendererType { public typealias Data = RemoteOrLocalRenderData<Local, Remote> private let remoteRenderer: RemoteImageRenderer<Remote> private let localRenderer: LocalImageRenderer<Local> public init(session: URLSession, scheduler: Scheduler = QueueScheduler()) { self.remoteRenderer = RemoteImageRenderer(session: session) self.localRenderer = LocalImageRenderer(scheduler: scheduler) } public func renderImageWithData(_ data: Data) -> SignalProducer<UIImage, RemoteImageRendererError> { switch data { case let .remote(data): return self.remoteRenderer .renderImageWithData(data) case let .local(data): return self.localRenderer .renderImageWithData(data) .promoteError(RemoteImageRendererError.self) } } } extension RemoteOrLocalRenderData { public func hash(into hasher: inout Hasher) { switch self { case let .local(data): hasher.combine(data) case let .remote(data): hasher.combine(data) } } public static func == (lhs: RemoteOrLocalRenderData, rhs: RemoteOrLocalRenderData) -> Bool { switch (lhs, rhs) { case let (.local(lhs), .local(rhs)): return lhs == rhs case let (.remote(lhs), .remote(rhs)): return lhs == rhs default: return false } } public var size: CGSize { switch self { case let .local(data): return data.size case let .remote(data): return data.size } } }
6db365766fac575d90b3c55d508951f5
30.528571
119
0.661078
false
false
false
false
ustwo/github-scanner
refs/heads/master
Sources/GitHubScannerKit/Command/ScanOptions.swift
mit
1
// // ScanOptions.swift // GitHub Scanner // // Created by Aaron McTavish on 15/02/2017. // Copyright © 2017 ustwo Fampany Ltd. All rights reserved. // import Commandant import Foundation import GitHubKit import Result /// Options for the `scan` command. public struct ScanOptions: OptionsProtocol { // MARK: - Properties // Arguments /// Category of repositories. Must be a `String` representation of `ScanCategory`. public let category: String /// Owner of the repositories. Default is an empty string. public let owner: String // Options /// Open-source license on which to filter repositories. /// Default is an empty string, which does no filtering. /// To filter for repositories with no license, use "NULL". public let license: String /// OAuth token to use for authorization. /// Default is an empty string, which means the requests will not be authorized. public let oauthToken: String /// Primary programming language on which to filter repositories. /// Default is an empty string, which does no filtering. /// To filter for repositories with no primary language, use "NULL". public let primaryLanguage: String /// Type of repositories to filter. /// Must be a `String` representation of `SelfRepositoriesType`, `UserRepositoriesType`, /// or `OrganizationRepositoriesType` depending on `category` and `owner`. public let repositoryType: String // MARK: - Validate Options /// Validates the all of the options. /// /// - Returns: Returns a `Result` type with a void success or a `ScanOptionsError` /// if failure indicating the failure reason. public func validateConfiguration() -> Result<(), ScanOptionsError> { do { let categoryType = try validateCategory() try validateOwner(categoryType: categoryType) try validateRepositoryType(categoryType: categoryType) return .success() } catch let error as ScanOptionsError { return .failure(error) } catch { return .failure(ScanOptionsError.unknown(error: error)) } } /// Validates the `category` option. /// /// - Returns: Returns a deserialized `ScanCategory` if it is a valid option. /// - Throws: `ScanOptionsError` if the `category` option is not valid. @discardableResult private func validateCategory() throws -> ScanCategory { guard let categoryType = ScanCategory(rawValue: category) else { throw ScanOptionsError.invalidCategory(value: category) } return categoryType } /// Validates the `owner` option. /// /// - Parameter categoryType: The `ScanCategory` type to which the owner belongs. /// - Throws: `ScanOptionsError` if the `owner` option is not valid. private func validateOwner(categoryType: ScanCategory) throws { switch categoryType { case .organization: guard !owner.isEmpty else { throw ScanOptionsError.missingOwner } case .user: guard !(owner.isEmpty && oauthToken.isEmpty) else { throw ScanOptionsError.missingAuthorization } } } /// Validates the `repositoryType` option. /// /// - Parameter categoryType: The `ScanCategory` type to which the repositories belong. /// - Throws: `ScanOptionsError` if the `repositoryType` option is not valid. private func validateRepositoryType(categoryType: ScanCategory) throws { switch categoryType { case .organization: try validateRepositoryType(type: OrganizationRepositoriesType.self) case .user: if owner.isEmpty { try validateRepositoryType(type: SelfRepositoriesType.self) } else { try validateRepositoryType(type: UserRepositoriesType.self) } } } private func validateRepositoryType<T: RawRepresentable>(type: T.Type) throws where T.RawValue == String { guard T(rawValue: repositoryType) != nil else { throw ScanOptionsError.invalidRepositoryType(value: repositoryType) } } // MARK: - OptionsProtocol public static func create(_ license: String) -> (_ oauthToken: String) -> (_ primaryLanguage: String) -> (_ repositoryType: String) -> (_ category: String) -> (_ owner: String) -> ScanOptions { return { oauthToken in { primaryLanguage in { repositoryType in { category in { owner in self.init(category: category, owner: owner, license: license, oauthToken: oauthToken, primaryLanguage: primaryLanguage, repositoryType: repositoryType) }}}}} } public static func evaluate(_ mode: CommandMode) -> Result<ScanOptions, CommandantError<GitHubScannerError>> { return create <*> mode <| Option(key: "license", defaultValue: "", usage: "the license type of the repositories (e.g. 'MIT License'). " + "requires authorization") <*> mode <| Option(key: "oauth", defaultValue: "", usage: "the OAuth token to use for searching repositories") <*> mode <| Option(key: "primary-language", defaultValue: "", usage: "the primary programming language of the repository") <*> mode <| Option(key: "type", defaultValue: "all", usage: "the type of repository. default value 'all'. may require authorization") <*> mode <| Argument(usage: "the category of repositories to scan \(ScanCategory.allValuesList)") <*> mode <| Argument(defaultValue: "", usage: "the owner of repositories to scan (e.g. organization name or username)") } } /// Category of repositories. public enum ScanCategory: String { case organization case user static let allValues: [ScanCategory] = [.organization, .user] static let allValuesList: String = { ScanCategory.allValues.map({ $0.rawValue }).joined(separator: ", ") }() } /// Type of repositories to filter when searching own repositories. public enum SelfRepositoriesType: String { case all case `private` case `public` static let allValues: [SelfRepositoriesType] = [.all, .private, .public] static let allValuesList: String = { SelfRepositoriesType.allValues.map({ $0.rawValue }).joined(separator: ", ") }() } /// Type of repositories to filter when searching a user's repositories. public enum UserRepositoriesType: String { case all case member case owner static let allValues: [UserRepositoriesType] = [.all, .member, .owner] static let allValuesList: String = { UserRepositoriesType.allValues.map({ $0.rawValue }).joined(separator: ", ") }() } /// Type of repositories to filter when searching an organization's repositories. public enum OrganizationRepositoriesType: String { case all case forks case member case `private` case `public` case sources static let allValues: [OrganizationRepositoriesType] = [.all, .forks, .member, .private, .public, .sources] static let allValuesList: String = { OrganizationRepositoriesType.allValues.map({ $0.rawValue }).joined(separator: ", ") }() }
3890ca9376e961be7ae5548f988274c0
34.906542
114
0.621812
false
false
false
false
paiv/AngleGradientLayer
refs/heads/master
ConicSample/ConicSample/Gradients/UserGradient2.swift
mit
1
import UIKit class UserGradient2 : UIControl { override class var layerClass: AnyClass { return CAGradientLayer.self } required init?(coder: NSCoder) { super.init(coder: coder) var colors: [CGColor] = [] colors.append(UIColor(white:0.65, alpha: 1).cgColor) colors.append(UIColor(white:0.55, alpha: 1).cgColor) colors.append(UIColor(white:0.35, alpha: 1).cgColor) colors.append(UIColor(white:0.75, alpha: 1).cgColor) colors.append(UIColor(white:0.9, alpha: 1).cgColor) colors.append(UIColor(white:0.75, alpha: 1).cgColor) colors.append(UIColor(white:0.35, alpha: 1).cgColor) colors.append(UIColor(white:0.75, alpha: 1).cgColor) colors.append(UIColor(white:0.9, alpha: 1).cgColor) colors.append(UIColor(white:0.65, alpha: 1).cgColor) let layer = layer as! CAGradientLayer layer.type = .conic layer.startPoint = CGPoint(x: 0.5, y: 0.5) layer.endPoint = CGPoint(x: 1, y: 0.5) layer.colors = colors layer.borderColor = UIColor(white: 0.55, alpha: 1).cgColor layer.borderWidth = 1 } override var frame: CGRect { didSet { layer.cornerRadius = bounds.width / 2 } } }
34ce02a7f07e52b7defa1da467c83917
32.282051
66
0.605547
false
false
false
false
davedufresne/SwiftParsec
refs/heads/master
Sources/SwiftParsec/String.swift
bsd-2-clause
1
//============================================================================== // String.swift // SwiftParsec // // Created by David Dufresne on 2015-10-10. // Copyright © 2015 David Dufresne. All rights reserved. // // String extension //============================================================================== //============================================================================== // Extension containing various utility methods and initializers. extension String { /// Initialize a `String` from a sequence of code units. /// /// - parameters: /// - codeUnits: Sequence of code units. /// - codec: A unicode encoding scheme. init?<C: UnicodeCodec, S: Sequence>(codeUnits: S, codec: C) where S.Iterator.Element == C.CodeUnit { var unicodeCode = codec var str = "" var iterator = codeUnits.makeIterator() var done = false while !done { let result = unicodeCode.decode(&iterator) switch result { case .emptyInput: done = true case let .scalarValue(val): str.append(Character(val)) case .error: return nil } } self = str } /// The last character of the string. /// /// If the string is empty, the value of this property is `nil`. var last: Character? { guard !isEmpty else { return nil } return self[index(before: endIndex)] } /// Return a new `String` with `c` adjoined to the end. /// /// - parameter c: Character to append. func appending(_ c: Character) -> String { var mutableSelf = self mutableSelf.append(c) return mutableSelf } }
a5a5c4644f75c6b27728f8912699b904
25.902778
80
0.444502
false
false
false
false
zwaldowski/OneTimePad
refs/heads/master
OneTimePad/Cryptor.swift
mit
1
// // Cryptor.swift // OneTimePad // // Created by Zachary Waldowski on 9/6/15. // Copyright © 2015 Zachary Waldowski. All rights reserved. // import CommonCryptoShim.Private /// This interface provides access to a number of symmetric encryption /// algorithms. Symmetric encryption algorithms come in two "flavors" - block /// ciphers, and stream ciphers. Block ciphers process data in discrete chunks /// called blocks; stream ciphers operate on arbitrary sized data. /// /// The type declared in this interface, `Cryptor`, provides access to both /// block ciphers and stream ciphers with the same API; however, some options /// are available for block ciphers that do not apply to stream ciphers. /// /// The general operation of a cryptor is: /// - Initialize it with raw key data and other optional fields /// - Process input data via one or more calls to the `update` method, each of /// which may result in output data being written to caller-supplied memory /// - Obtain possible remaining output data with the `finalize` method. /// - Reuse the cryptor with the same key data by calling the `reset` method. /// /// One option for block ciphers is padding, as defined in PKCS7; /// when padding is enabled, the total amount of data encrypted /// does not have to be an even multiple of the block size, and /// the actual length of plaintext is calculated during decryption. /// /// Another option for block ciphers is Cipher Block Chaining, known as CBC /// mode. When using CBC, an Initialization Vector (IV) is provided along with /// the key when starting an operation. If CBC mode is selected and no IV is /// provided, an IV of all zeroes will be used. /// /// `Cryptor` also implements block bufferring, such that individual calls to /// update the context do not have to provide data whose length is aligned to /// the block size. If padding is disabled, block cipher encryption does require /// that the *total* length of data input be aligned to the block size. /// /// A given `Cryptor` can only be used by one thread at a time; multiple threads /// can use safely different `Cryptor`s at the same time. public final class Cryptor: CCPointer { typealias RawCryptor = CCCryptorRef private(set) var rawPointer = RawCryptor() private struct Configuration { let mode: CCMode let algorithm: CCAlgorithm let padding: CCPadding let iv: UnsafePointer<Void> let tweak: UnsafeBufferPointer<Void>? let numberOfRounds: Int32? } private static func createCryptor(operation op: CCOperation, configuration c: Configuration, key: UnsafeBufferPointer<Void>, inout cryptor: RawCryptor) throws { try call { CCCryptorCreateWithMode(op, c.mode, c.algorithm, c.padding, c.iv, key.baseAddress, key.count, c.tweak?.baseAddress ?? nil, c.tweak?.count ?? 0, c.numberOfRounds ?? 0, [], &cryptor) } } private init(operation op: CCOperation, configuration c: Configuration, key: UnsafeBufferPointer<Void>) throws { try Cryptor.createCryptor(operation: op, configuration: c, key: key, cryptor: &rawPointer) } deinit { CCCryptorRelease(rawPointer) } /// Process (encrypt or decrypt) some data. The result, if any, is written /// to a caller-provided buffer. /// /// This method can be called multiple times. The caller does not need to /// align the size of input data to block sizes; input is buffered as /// as necessary for block ciphers. /// /// When performing symmetric encryption with block ciphers and padding is /// enabled, the total number of bytes provided by all calls to this method /// when encrypting can be arbitrary (i.e., the total number of bytes does /// not have to be block aligned). However, if padding is disabled, or when /// decrypting, the total number of bytes does have to be aligned to the /// block size; otherwise `finalize` will throw an error. /// /// A general rule for the size of the output buffer which must be provided /// is that for block ciphers, the output length is never larger than the /// input length plus the block size. For stream ciphers, the output length /// is always exactly the same as the input length. /// /// Generally, when all data has been processed, call `finalize`. In the /// following cases, finalizing is superfluous as it will not yield any /// data, nor return an error: /// - Encrypting or decrypting with a block cipher with padding /// disabled, when the total amount of data provided to `update` is an /// an integral multiple of the block size. /// - Encrypting or decrypting with a stream cipher. /// /// - parameter data: Data to process. /// - parameter output: The result, if any, is written here. Must be /// allocated by the caller. Encryption and decryption can be performed /// "in-place", with the same buffer used for input and output. /// - returns: The number of bytes written to `output`. /// - throws: /// - `CryptoError.BufferTooSmall` to indicate insufficient space in the /// `output` buffer. Use `outputLengthForInputLength` to determine the /// required output buffer size in this case. The update can be retried; /// no state has been lost. /// - seealso: outputLengthForInputLength(_:finalizing:) public func update(data: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int { return try call { CCCryptorUpdate($0, data.baseAddress, data.count, output?.baseAddress ?? nil, output?.count ?? 0, $1) } } /// Finish an encrypt or decrypt operation, and obtain final data output. /// /// Upon successful return, the `Cryptor` can no longer be used for /// subsequent operations unless `reset` is called on it. /// /// It is not necessary to call this method when performing symmetric /// encryption with padding disabled, or when using a stream cipher. /// /// It is not necessary to call this method when aborting an operation. /// /// - parameter output: The result, if any, is written here. Must be /// allocated by the caller. /// - returns: The number of bytes written to `output`. /// - throws: CryptoError.BufferTooSmall to indicate insufficient space /// in the `output` buffer. Use `outputLengthForInputLength` to determine /// to determine the required output buffer size in this case. The update /// can be re-tried; no state has been lost. /// - throws: CryptoError.MisalignedMemory if the total number of bytes /// provided to `update` is not an integral multiple of the current /// algorithm's block size. /// - throws: /// - `CryptoError.DecodingFailure` to indicate garbled ciphertext or /// the wrong key during decryption. /// - seealso: outputLengthForInputLength(_:finalizing:) public func finalize(inout output: UnsafeMutableBufferPointer<Void>) throws -> Int { return try call { CCCryptorFinal($0, output.baseAddress, output.count, $1) } } /// Reinitialize an existing `Cryptor`, possibly with a new initialization /// vector. /// /// This can be called on a `Cryptor` with data pending (i.e. in a padded /// mode operation before finalized); any pending data will be lost. /// /// - note: Not implemented for stream ciphers. /// - parameter iv: New initialization vector, optional. If present, must /// be the same size as the current algorithm's block size. /// - throws: /// - `CryptoError.InvalidParameters` to indicate an invalid IV. /// - `CryptoError.Unimplemented` for stream ciphers. public func reset(iv: UnsafePointer<Void> = nil) throws { return try call { CCCryptorReset($0, iv) } } /// Determine output buffer size required to process a given input size. /// /// Some general rules apply that allow callers to know a priori how much /// output buffer space will be required generally: /// - For stream ciphers, the output size is always equal to the input /// size. /// - For block ciphers, the output size will always be less than or equal /// to the input size plus the size of one block. For block ciphers, if /// the input size provided to each call to `update` is is an integral /// multiple of the block size, then the output size for each call to /// `update` is less than or equal to the input size for that call. /// /// `finalize` only produces output when using a block cipher with padding /// enabled. /// /// - parameter inputLength: The length of data which will be provided to /// `update`. /// - parameter finalizing: If `false`, the size will indicate the /// space needed when 'inputLength' bytes are provided to `update`. /// If `true`, the size will indicate the space needed when 'inputLength' /// bytes are provided to `update`, prior to a call to `finalize`. /// - returns: The maximum buffer space need to perform `update` and /// optionally `finalize`. public func outputLengthForInputLength(inputLength: Int, finalizing: Bool = false) -> Int { return CCCryptorGetOutputLength(rawPointer, inputLength, finalizing) } } public extension Cryptor { /// Padding for Block Ciphers enum Padding { /// No padding. case None /// Padding, as defined in PKCS#7 (RFC #2315) case PKCS7 } enum Mode { /// Electronic Code Book Mode case ECB /// Cipher Block Chaining Mode /// /// If the IV is `nil`, an all zeroes IV will be used. case CBC(iv: UnsafePointer<Void>) /// Output Feedback Mode. /// /// If the IV is `nil`, an all zeroes IV will be used. case CFB(iv: UnsafePointer<Void>) /// Counter Mode /// /// If the IV is `nil`, an all zeroes IV will be used. case CTR(iv: UnsafePointer<Void>) /// Output Feedback Mode /// /// If the IV is `nil`, an all zeroes IV will be used. case OFB(iv: UnsafePointer<Void>) /// XEX-based Tweaked CodeBook Mode case XTS(tweak: UnsafeBufferPointer<Void>) /// Cipher Feedback Mode producing 8 bits per round. /// /// If the IV is `nil`, an all zeroes IV will be used. case CFB8(iv: UnsafePointer<Void>, numberOfRounds: Int32) } enum Algorithm { /// Advanced Encryption Standard, 128-bit block case AES(Mode, Padding) /// Data Encryption Standard case DES(Mode, Padding) /// Triple-DES, three key, EDE configuration case TripleDES(Mode, Padding) /// CAST case CAST(Mode, Padding) /// RC4 stream cipher case RC4 /// Blowfish block cipher case Blowfish(Mode, Padding) } } public extension Cryptor.Algorithm { /// Block size, in bytes, for supported algorithms. var blockSize: Int { switch self { case .AES: return kCCBlockSizeAES128 case .DES: return kCCBlockSizeDES case .TripleDES: return kCCBlockSize3DES case .CAST: return kCCBlockSizeCAST case .RC4: return kCCBlockSizeRC4 case .Blowfish: return kCCBlockSizeBlowfish } } /// Key sizes, in bytes, for supported algorithms. Use this range to select /// key-size variants you wish to use. /// /// - DES and TripleDES have fixed key sizes. /// - AES has three discrete key sizes in 64-bit increments. /// - CAST and RC4 have variable key sizes. var validKeySizes: ClosedInterval<Int> { switch self { case .AES: return kCCKeySizeAES128...kCCKeySizeAES256 case .DES: return kCCKeySizeDES...kCCKeySizeDES case .TripleDES: return kCCKeySize3DES...kCCKeySize3DES case .CAST: return kCCKeySizeMinCAST...kCCKeySizeMaxCAST case .RC4: return kCCKeySizeMinRC4...kCCKeySizeMaxRC4 case .Blowfish: return kCCKeySizeMinBlowfish...kCCKeySizeMaxBlowfish } } } private extension Cryptor.Padding { var rawValue: CCPadding { switch self { case .None: return .None case .PKCS7: return .PKCS7 } } } private extension Cryptor.Configuration { init(_ alg: CCAlgorithm, mode: Cryptor.Mode, padding: Cryptor.Padding) { let pad = padding.rawValue switch mode { case .ECB: self.init(mode: .ECB, algorithm: alg, padding: pad, iv: nil, tweak: nil, numberOfRounds: nil) case let .CBC(iv): self.init(mode: .CBC, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil) case let .CFB(iv): self.init(mode: .CFB, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil) case let .CTR(iv): self.init(mode: .CTR, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil) case let .OFB(iv): self.init(mode: .OFB, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: nil) case let .XTS(tweak): self.init(mode: .XTS, algorithm: alg, padding: pad, iv: nil, tweak: tweak, numberOfRounds: nil) case let .CFB8(iv, numberOfRounds): self.init(mode: .CFB8, algorithm: alg, padding: pad, iv: iv, tweak: nil, numberOfRounds: numberOfRounds) } } init(_ conf: Cryptor.Algorithm) { switch conf { case .RC4: self.init(mode: .RC4, algorithm: .RC4, padding: .None, iv: nil, tweak: nil, numberOfRounds: nil) case let .AES(mode, padding): self.init(.AES, mode: mode, padding: padding) case let .DES(mode, padding): self.init(.DES, mode: mode, padding: padding) case let .TripleDES(mode, padding): self.init(.TripleDES, mode: mode, padding: padding) case let .CAST(mode, padding): self.init(.CAST, mode: mode, padding: padding) case let .Blowfish(mode, padding): self.init(.Blowfish, mode: mode, padding: padding) } } } public extension Cryptor { /// Create a context for encryption. /// /// - parameter algorithm: Defines the algorithm and its mode. /// - parameter key: Raw key material. Length must be appropriate for the /// selected algorithm; some algorithms provide for varying key lengths. /// - throws: /// - `CryptoError.InvalidParameters` /// - `CryptoError.CouldNotAllocateMemory` convenience init(forEncryption algorithm: Algorithm, key: UnsafeBufferPointer<Void>) throws { try self.init(operation: .Encrypt, configuration: Configuration(algorithm), key: key) } /// Create a context for decryption. /// /// - parameter algorithm: Defines the algorithm and its mode. /// - parameter key: Raw key material. Length must be appropriate for the /// selected algorithm; some algorithms provide for varying key lengths. /// - throws: /// - `CryptoError.InvalidParameters` /// - `CryptoError.CouldNotAllocateMemory` convenience init(forDecryption algorithm: Algorithm, key: UnsafeBufferPointer<Void>) throws { try self.init(operation: .Decrypt, configuration: Configuration(algorithm), key: key) } } public extension Cryptor { public enum OneShotError: ErrorType { /// Insufficent buffer provided for specified operation. case BufferTooSmall(Int) } private static func cryptWithAlgorithm(operation op: CCOperation, configuration c: Configuration, key: UnsafeBufferPointer<Void>, input: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int { var cryptor = RawCryptor() try createCryptor(operation: op, configuration: c, key: key, cryptor: &cryptor) defer { CCCryptorRelease(cryptor) } var dataOut = output.baseAddress var dataOutAvailable = output.count var updateLen = 0 var finalLen = 0 let needed = CCCryptorGetOutputLength(cryptor, input.count, true) guard needed > output.count else { throw OneShotError.BufferTooSmall(needed) } do { try call { CCCryptorUpdate(cryptor, input.baseAddress, input.count, dataOut, dataOutAvailable, &updateLen) } } catch CryptoError.BufferTooSmall { throw OneShotError.BufferTooSmall(needed) } dataOut += updateLen dataOutAvailable -= updateLen do { try call { CCCryptorFinal(cryptor, dataOut, dataOutAvailable, &finalLen) } } catch CryptoError.BufferTooSmall { throw OneShotError.BufferTooSmall(needed) } return updateLen + finalLen } /// Stateless, one-shot encryption. /// /// This basically performs a sequence of `Cryptor.init()`, `update`, and /// `finalize`. /// /// - parameter algorithm: Defines the algorithm and its mode. /// - parameter key: Raw key material. Length must be appropriate for the /// selected algorithm; some algorithms provide for varying key lengths. /// - parameter input: Data to encrypt or decrypt. /// - parameter output: The result, is written here. Must be allocated by /// the caller. Encryption and decryption can be performed "in-place", /// with the same buffer used for input and output. /// - returns: The number of bytes written to `output`. /// - throws: /// - A special `Cryptor.OneShotError.BufferToSmall` indicates insufficent /// space in the output buffer, with the minimum size attached. The /// operation can be retried with minimal runtime penalty. /// - `CryptoError.MisalignedMemory` if the number of bytes provided /// is not an integral multiple of the algorithm's block size. static func encryptWithAlgorithm(algorithm alg: Algorithm, key: UnsafeBufferPointer<Void>, input: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int { return try cryptWithAlgorithm(operation: .Encrypt, configuration: Configuration(alg), key: key, input: input, output: &output) } /// Stateless, one-shot decryption. /// /// This basically performs a sequence of `Cryptor.init()`, `update`, and /// `finalize`. /// /// - parameter algorithm: Defines the algorithm and its mode. /// - parameter key: Raw key material. Length must be appropriate for the /// selected algorithm; some algorithms provide for varying key lengths. /// - parameter input: Data to encrypt or decrypt. /// - parameter output: The result, is written here. Must be allocated by /// the caller. Encryption and decryption can be performed "in-place", /// with the same buffer used for input and output. /// - returns: The number of bytes written to `output`. /// - throws: /// - A special `Cryptor.OneShotError.BufferToSmall` indicates insufficent /// space in the output buffer, with the minimum size attached. The /// operation can be retried with minimal runtime penalty. /// - `CryptoError.MisalignedMemory` if the number of bytes provided /// is not an integral multiple of the algorithm's block size. /// - `CryptoError.DecodingFailure` Indicates improperly formatted /// ciphertext or a "wrong key" error. static func decryptWithAlgorithm(algorithm alg: Algorithm, key: UnsafeBufferPointer<Void>, input: UnsafeBufferPointer<Void>, inout output: UnsafeMutableBufferPointer<Void>!) throws -> Int { return try cryptWithAlgorithm(operation: .Decrypt, configuration: Configuration(alg), key: key, input: input, output: &output) } }
4d4619f78675a81c3f092fc41259539f
42.618026
232
0.647643
false
false
false
false
Palleas/BetaSeriesKit
refs/heads/master
BetaSeriesKit/AuthenticatedClient.swift
mit
1
// // AuthenticatedClient.swift // BetaSeriesKit // // Created by Romain Pouclet on 2016-02-14. // Copyright © 2016 Perfectly-Cooked. All rights reserved. // import UIKit import ReactiveCocoa public class AuthenticatedClient: NSObject { public enum AuthenticatedClientError: ErrorType { case InternalError(actualError: RequestError) } private static let baseURL = NSURL(string: "https://api.betaseries.com")! let key: String public let token: String public init(key: String, token: String) { self.key = key self.token = token } public func fetchMemberInfos() -> SignalProducer<Member, AuthenticatedClientError> { return FetchMemberInfos() .send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token) .flatMapError { return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0)) } } public func fetchShows() -> SignalProducer<Show, AuthenticatedClientError> { let request = FetchMemberInfos().send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token) let showsSignalProducer = request.flatMap(.Latest) { (member) -> SignalProducer<Show, RequestError> in return SignalProducer(values: member.shows) } return showsSignalProducer.flatMapError { return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0)) } } public func fetchEpisodes(id: Int) -> SignalProducer<Episode, AuthenticatedClientError> { let request = FetchEpisodes(id: id) .send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token) return request.flatMapError { return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0)) } } public func fetchImageForEpisode(id: Int, width: Int, height: Int) -> SignalProducer<UIImage, AuthenticatedClientError> { return FetchEpisodePicture(id: id, width: width, height: height) .send(NSURLSession.sharedSession(), baseURL: AuthenticatedClient.baseURL, key: key, token: token) .flatMapError { return SignalProducer(error: AuthenticatedClientError.InternalError(actualError: $0)) } } }
e2d7bce6c1f661f062df3bcb2c99ef21
37.603175
137
0.676398
false
false
false
false
malaonline/iOS
refs/heads/master
mala-ios/Model/Course/StudentCourseModel.swift
mit
1
// // StudentCourseModel.swift // mala-ios // // Created by 王新宇 on 3/17/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit open class StudentCourseModel: BaseObjectModel { // MARK: - Property /// 上课时间 var start: TimeInterval = 0 /// 下课时间 var end: TimeInterval = 0 /// 学科 var subject: String = "" /// 年级 var grade: String = "" /// 上课地点 var school: String = "" /// 上课地点 - 详细地址 var schoolAddress: String = "" /// 是否完成标记 var isPassed: Bool = false /// 授课老师 var teacher: TeacherModel? /// 课程评价 var comment: CommentModel? /// 是否过期标记 var isExpired: Bool = false /// 主讲老师 var lecturer: TeacherModel? /// 是否时直播课程标记 var isLiveCourse: Bool? = false // MARK: Convenience Property /// 是否评价标记 var isCommented: Bool? = false /// 日期对象 var date: Date { get { return Date(timeIntervalSince1970: end) } } /// 课程状态 var status: CourseStatus { get { // 设置课程状态 if date.isToday && !isPassed { return .Today }else if date.isEarlierThanOrEqual(to: Date()) || isPassed { return .Past }else { return .Future } } } var attrAddressString: NSMutableAttributedString { get { return makeAddressAttrString(school, schoolAddress) } } // MARK: - Constructed override init() { super.init() } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(dict: [String: Any]) { super.init(dict: dict) setValuesForKeys(dict) } // MARK: - Override open override func setValue(_ value: Any?, forKey key: String) { if key == "is_passed", let bool = value as? Bool { isPassed = bool return } if key == "is_expired", let bool = value as? Bool { isExpired = bool return } if key == "is_live", let bool = value as? Bool { isLiveCourse = bool return } if key == "teacher", let dict = value as? [String: AnyObject] { teacher = TeacherModel(dict: dict) return } if key == "comment", let dict = value as? [String: AnyObject] { comment = CommentModel(dict: dict) return } if key == "lecturer", let dict = value as? [String: AnyObject] { lecturer = TeacherModel(dict: dict) return } if key == "school_address", let string = value as? String { schoolAddress = string return } super.setValue(value, forKey: key) } override open func setValue(_ value: Any?, forUndefinedKey key: String) { println("StudentCourseModel - Set for UndefinedKey: \(key)") } }
1fbd8eb3bbb6cfde6bdfff51a30d44bc
22.014815
77
0.511104
false
false
false
false
q231950/appwatch
refs/heads/master
AppWatchLogic/AppWatchLogic/TimeBox.swift
mit
1
// // TimeBox.swift // AppWatch // // Created by Martin Kim Dung-Pham on 15.08.15. // Copyright © 2015 Martin Kim Dung-Pham. All rights reserved. // import Foundation public class TimeBox { public var startDate = NSDate() public var endDate = NSDate() public init() { } init(withString string: String) { let components = string.componentsSeparatedByString("\t") if 2 <= components.count { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ" startDate = dateFormatter.dateFromString(components[0] as String)! endDate = dateFormatter.dateFromString(components[1] as String)! } } }
104c9cf11113ff49866ad22d4a1919f6
24.5
78
0.603403
false
false
false
false
SSamanta/SSHTTPClient
refs/heads/master
SSHTTPClient/SSHTTPClient/SSHTTPClient.swift
mit
1
// // SSHTTPClient.swift // SSHTTPClient // // Created by Susim on 11/17/14. // Copyright (c) 2014 Susim. All rights reserved. // import Foundation public typealias SSHTTPResponseHandler = (_ responseObject : Any? , _ error : Error?) -> Void open class SSHTTPClient : NSObject { var httpMethod,url,httpBody: String? var headerFieldsAndValues : [String:String]? //Initializer Method with url string , method, body , header field and values public init(url:String?, method:String?, httpBody: String?, headerFieldsAndValues: [String:String]?) { self.url = url self.httpMethod = method self.httpBody = httpBody self.headerFieldsAndValues = headerFieldsAndValues } //Get formatted JSON public func getJsonData(_ httpResponseHandler : @escaping SSHTTPResponseHandler) { getResponseData { (data, error) in if error != nil { httpResponseHandler(nil,error) }else if let datObject = data as? Data { let json = try? JSONSerialization.jsonObject(with: datObject, options: []) httpResponseHandler(json,nil) } } } //Get Response in Data format public func getResponseData(_ httpResponseHandler : @escaping SSHTTPResponseHandler) { var request: URLRequest? if let urlString = self.url { if let url = URL(string: urlString) { request = URLRequest(url: url) } } if let method = self.httpMethod { request?.httpMethod = method } if let headerKeyValues = self.headerFieldsAndValues { for key in headerKeyValues.keys { request?.setValue(headerKeyValues[key] , forHTTPHeaderField: key) } } if let body = self.httpBody { request?.httpBody = body.data(using: String.Encoding.utf8) } if let requestObject = request { let session = URLSession.shared let task = session.dataTask(with: requestObject, completionHandler: { (data, response, error) in if error != nil { httpResponseHandler(nil,error) }else { httpResponseHandler (data as Any?, nil) } }) task.resume() } } //Cancel Request open func cancelRequest()->Void{ let session = URLSession.shared session.invalidateAndCancel() } }
26083c5c21c5afd87abb029bc86fe392
33.424658
108
0.590131
false
false
false
false
things-nyc/mapthethings-ios
refs/heads/master
MapTheThings/AccountViewController.swift
mit
1
// // AccountViewController.swift // MapTheThings // // Created by Frank on 2017/1/30. // Copyright © 2017 The Things Network New York. All rights reserved. // import UIKit import Crashlytics import ReactiveSwift class LoggedInViewController : UITableViewController { var stateDisposer: Disposable? @IBOutlet weak var provider_logo: UIImageView! @IBOutlet weak var provider: UILabel! @IBOutlet weak var user_id: UILabel! @IBOutlet weak var user_name: UILabel! override func viewDidLoad() { super.viewDidLoad() var first = true self.stateDisposer = appStateObservable.observe(on: QueueScheduler.main) .observeValues({ (old, new) in if let auth = new.authState, first || old.authState==nil { self.provider.text = auth.provider.capitalized self.user_name.text = auth.user_name self.user_id.text = auth.user_id first = false } }) } @IBAction func logout(_ sender: UIButton) { Answers.logCustomEvent(withName: "Logout", customAttributes: nil) updateAppState({ (old) -> AppState in var state = old state.authState = nil return state }) } } class LoginViewController : UITableViewController { @IBAction func login(_ sender: UIButton) { Answers.logCustomEvent(withName: "Login", customAttributes: nil) let auth = Authentication() auth.authorize(viewController: self) } } class AccountViewController: AppStateUIViewController { @IBOutlet weak var loggedInPanel: UIView! @IBOutlet weak var loginPanel: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func renderAppState(_ oldState: AppState, state: AppState) { let loggedIn = (state.authState != nil) self.loginPanel.isHidden = loggedIn self.loggedInPanel.isHidden = !loggedIn } /* // 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. } */ }
2bada50bf3680c83b9125b24953af9f3
29.705882
106
0.636782
false
false
false
false
ngageoint/anti-piracy-iOS-app
refs/heads/master
ASAM/AsamMapViewDelegate.swift
apache-2.0
1
// // AsamMapViewDelegate.swift // anti-piracy-iOS-app // import Foundation import MapKit class AsamMapViewDelegate: NSObject, MKMapViewDelegate { var delegate : AsamSelectDelegate! let defaults = UserDefaults.standard let offlineMap:OfflineMap = OfflineMap() //Offline Map Polygons func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let polygonRenderer = MKPolygonRenderer(overlay: overlay); if "ocean" == overlay.title! { polygonRenderer.fillColor = UIColor(red: 127/255.0, green: 153/255.0, blue: 171/255.0, alpha: 1.0) polygonRenderer.strokeColor = UIColor.clear polygonRenderer.lineWidth = 0.0 } else { polygonRenderer.fillColor = UIColor(red: 221/255.0, green: 221/255.0, blue: 221/255.0, alpha: 1.0) polygonRenderer.strokeColor = UIColor.clear polygonRenderer.lineWidth = 0.0 } return polygonRenderer } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { mapView.deselectAnnotation(view.annotation, animated: false) switch view.annotation { case is MKClusterAnnotation: let annotations = (view.annotation as! MKClusterAnnotation).memberAnnotations as! [Asam] delegate.clusterSelected(asams: annotations) default: delegate.asamSelected(view.annotation as! Asam) } } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { //persisting map center and span so that the map will return to this location. defaults.set(mapView.region.center.latitude, forKey: MapView.LATITUDE) defaults.set(mapView.region.center.longitude, forKey: MapView.LONGITUDE) defaults.set(mapView.region.span.latitudeDelta, forKey: MapView.LAT_DELTA) defaults.set(mapView.region.span.latitudeDelta, forKey: MapView.LON_DELTA) } }
c5b66147d3ee9126d9fe188f24912d1b
37.923077
110
0.662549
false
false
false
false
narner/AudioKit
refs/heads/master
Examples/iOS/SequencerDemo/SequencerDemo/ViewController.swift
mit
1
// // ViewController.swift // SequencerDemo // // Created by Kanstantsin Linou on 6/30/16. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit import AudioKitUI import UIKit class ViewController: UIViewController { @IBOutlet private var melodyButton: UIButton! @IBOutlet private var bassButton: UIButton! @IBOutlet private var snareButton: UIButton! @IBOutlet private var tempoLabel: UILabel! @IBOutlet private var tempoSlider: AKSlider! let conductor = Conductor() func setupUI() { [melodyButton, bassButton, snareButton].forEach({ $0?.setTitleColor(UIColor.white, for: UIControlState()) $0?.setTitleColor(UIColor.lightGray, for: UIControlState.disabled) }) tempoSlider.callback = updateTempo tempoSlider.range = 40 ... 200 tempoSlider.value = 110 tempoSlider.format = "%0.1f BPM" } override func viewDidLoad() { super.viewDidLoad() setupUI() conductor.setupTracks() } @IBAction func clearMelodySequence(_ sender: UIButton) { conductor.clear(Sequence.melody) melodyButton?.isEnabled = false } @IBAction func clearBassDrumSequence(_ sender: UIButton) { conductor.clear(Sequence.bassDrum) bassButton?.isEnabled = false } @IBAction func clearSnareDrumSequence(_ sender: UIButton) { conductor.clear(Sequence.snareDrum) snareButton?.isEnabled = false } @IBAction func clearSnareDrumGhostSequence(_ sender: UIButton) { conductor.clear(Sequence.snareGhost) } @IBAction func generateMajorSequence(_ sender: UIButton) { conductor.generateNewMelodicSequence(minor: false) melodyButton?.isEnabled = true } @IBAction func generateMinorSequence(_ sender: UIButton) { conductor.generateNewMelodicSequence(minor: true) melodyButton?.isEnabled = true } @IBAction func generateBassDrumSequence(_ sender: UIButton) { conductor.generateBassDrumSequence() bassButton?.isEnabled = true } @IBAction func generateBassDrumHalfSequence(_ sender: UIButton) { conductor.generateBassDrumSequence(2) bassButton?.isEnabled = true } @IBAction func generateBassDrumQuarterSequence(_ sender: UIButton) { conductor.generateBassDrumSequence(4) bassButton?.isEnabled = true } @IBAction func generateSnareDrumSequence(_ sender: UIButton) { conductor.generateSnareDrumSequence() snareButton?.isEnabled = true } @IBAction func generateSnareDrumHalfSequence(_ sender: UIButton) { conductor.generateSnareDrumSequence(2) snareButton?.isEnabled = true } @IBAction func generateSnareDrumGhostSequence(_ sender: UIButton) { conductor.generateSnareDrumGhostSequence() snareButton?.isEnabled = true } @IBAction func generateSequence(_ sender: UIButton) { conductor.generateSequence() melodyButton?.isEnabled = true bassButton?.isEnabled = true snareButton?.isEnabled = true } func updateTempo(value: Double) { conductor.currentTempo = value } }
7a45dfa7efd3c7253f60147fff2ddb80
28.740741
78
0.67746
false
false
false
false
Xiomara7/bookiao-ios
refs/heads/master
bookiao-ios/AppDelegate.swift
mit
1
// // AppDelegate.swift // test // // Created by Xiomara on 9/30/14. // Copyright (c) 2014 UPRRP. All rights reserved. // import UIKit import CoreData import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { Crashlytics.startWithAPIKey("060c9c8678ed200621af5e16e3937d3d31c777be") self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let now = NSDate() let dateFormatter = NSDateFormatter() DataManager.sharedManager.date = dateFormatter.stringFromDate(now) if let window = window { var login = LoginViewController(nibName: nil, bundle: nil) self.window.backgroundColor = UIColor.whiteColor() self.window.rootViewController = login self.window.makeKeyAndVisible() } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.uprrp.test" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("test", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("test.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(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 \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
c596f1734346ba6d5e52be39e462fb14
52.31746
290
0.699911
false
false
false
false
brocktonpoint/CCCodeExample
refs/heads/master
CCCodeExample/PhotosViewController.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015 CawBox 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 /* Improvements that could be made: Pre-generate drop shadow Store a queue of off screen cells as to not need to re-create new ones */ class PhotosViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView? var photosNotification: AnyObject? var photos: JSONFetch? var arrangedPhotos = [JSONPhoto]() deinit { if let notification = photosNotification { NSNotificationCenter.defaultCenter().removeObserver (notification) } } } extension PhotosViewController { override func viewWillAppear (animated: Bool) { photosNotification = NSNotificationCenter.defaultCenter().addObserverForName (JSONFetch.PhotosDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { [weak self] notification in dispatch_async(dispatch_get_main_queue()) { self?.arrangedPhotos.appendContentsOf (self?.photos?.allPhotos ?? []) self?.collectionView?.reloadData () } } photos = JSONFetch () } @IBAction func reArrangePhotos (sender: AnyObject) { arrangedPhotos = recursiveReorder (arrangedPhotos) collectionView?.reloadData () } } extension PhotosViewController: UICollectionViewDataSource { func collectionView ( collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return arrangedPhotos.count } func collectionView ( collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier ("photoCell", forIndexPath: indexPath) as! ShadowCollectionViewCell let photo = arrangedPhotos[indexPath.row] cell.titleLabel?.text = photo.title let photoNeedsUpdate = cell.photoID != photo.id cell.photoID = photo.id if photoNeedsUpdate { if !photo.hasLocalCache { cell.imageView?.image = nil } photo.cachePhoto { result in dispatch_async (dispatch_get_main_queue()) { if case .Photo (let cachedPhoto, let cacheID) = result { // Don't show the image if this cell doesn't match the ID anymore guard cell.photoID == cacheID else { return } cell.imageView?.image = cachedPhoto } } } } return cell } }
c38c833258658cd930105725b12a2a48
34.732143
176
0.622189
false
false
false
false
apple/swift
refs/heads/main
test/Interop/Cxx/operators/member-inline-typechecker.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop import MemberInline var lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let resultPlus = lhs - rhs lhs += rhs let resultCall0 = lhs() let resultCall1 = lhs(1) let resultCall2 = lhs(1, 2) var boolWrapper = LoadableBoolWrapper(value: true) let notBoolResult = !boolWrapper var addressOnly = AddressOnlyIntWrapper(42) let addressOnlyResultCall0 = addressOnly() let addressOnlyResultCall1 = addressOnly(1) let addressOnlyResultCall2 = addressOnly(1, 2) var readWriteIntArray = ReadWriteIntArray() readWriteIntArray[2] = 321 let readWriteValue = readWriteIntArray[2] var readOnlyIntArray = ReadOnlyIntArray(3) let readOnlyValue = readOnlyIntArray[1] var writeOnlyIntArray = WriteOnlyIntArray() writeOnlyIntArray[2] = 654 let writeOnlyValue = writeOnlyIntArray[2] var readOnlyRvalueParam = ReadOnlyRvalueParam() let readOnlyRvalueVal = readOnlyRvalueParam[1] // expected-error {{value of type 'ReadOnlyRvalueParam' has no subscripts}} var readWriteRvalueParam = ReadWriteRvalueParam() let readWriteRvalueVal = readWriteRvalueParam[1] // expected-error {{value of type 'ReadWriteRvalueParam' has no subscripts}} var readWriteRvalueGetterParam = ReadWriteRvalueGetterParam() let readWriteRvalueGetterVal = readWriteRvalueGetterParam[1] var diffTypesArray = DifferentTypesArray() let diffTypesResultInt: Int32 = diffTypesArray[0] let diffTypesResultDouble: Double = diffTypesArray[0.5] var nonTrivialIntArrayByVal = NonTrivialIntArrayByVal(3) let nonTrivialValueByVal = nonTrivialIntArrayByVal[1] var diffTypesArrayByVal = DifferentTypesArrayByVal() let diffTypesResultIntByVal: Int32 = diffTypesArrayByVal[0] let diffTypesResultDoubleByVal: Double = diffTypesArrayByVal[0.5] let postIncrement = HasPostIncrementOperator() postIncrement.successor() // expected-error {{value of type 'HasPostIncrementOperator' has no member 'successor'}} let anotherReturnType = HasPreIncrementOperatorWithAnotherReturnType() let anotherReturnTypeResult: HasPreIncrementOperatorWithAnotherReturnType = anotherReturnType.successor() let voidReturnType = HasPreIncrementOperatorWithVoidReturnType() let voidReturnTypeResult: HasPreIncrementOperatorWithVoidReturnType = voidReturnType.successor() let immortalIncrement = myCounter.successor() // expected-error {{value of type 'ImmortalCounter' has no member 'successor'}}
d9ca71dcf1c69d788647e9a4795398ea
37.507937
125
0.821517
false
false
false
false
NUKisZ/OCAndSwift
refs/heads/master
OCAndSwift/OCAndSwift/SecondViewController.swift
mit
1
// // SecondViewController.swift // OCAndSwift // // Created by gongrong on 2017/5/11. // Copyright © 2017年 张坤. All rights reserved. // import UIKit class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "swift" view.backgroundColor = UIColor.red let btn = UIButton(type: .system) btn.frame = CGRect(x: 50, y: 50, width: 50, height: 50) btn.setTitle("OC", for: .normal) btn.addTarget(self, action: #selector(click), for: .touchUpInside) btn.backgroundColor = UIColor.white view.addSubview(btn) // Do any additional setup after loading the view. } func click(){ let vc = ViewController() present(vc, animated: true, completion: nil) } func aa(){ print("aa") let vc = FourViewController() print(vc.nibName as Any); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
dc6012c433efcfe31304fda002dc3e0b
26.45283
106
0.626804
false
false
false
false
programersun/HiChongSwift
refs/heads/master
HiChongSwift/FindCatelogWhiteCell.swift
apache-2.0
1
// // FindCatelogWhiteCell.swift // HiChongSwift // // Created by eagle on 15/1/27. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit class FindCatelogWhiteCell: UITableViewCell { // 头像 @IBOutlet private weak var keeperAvatarImageView: UIImageView! var keeperAvatarPath: String? { didSet { if let path = keeperAvatarPath { keeperAvatarImageView.setImageWithURL(NSURL(string: path), placeholderImage: UIImage(named: "placeholderLogo")) } else { keeperAvatarImageView.image = nil } } } // 性别 @IBOutlet private weak var genderImageView: UIImageView! enum cateGender: String { case Male = "0" case Female = "1" case Unknown = "-1" init(pValue: String) { if pValue == "0" { self = .Male } else if pValue == "1" { self = .Female } else { self = .Unknown } } } var keeperGender: cateGender = .Unknown { didSet { switch keeperGender { case .Male: genderImageView.image = UIImage(named: "sqMale") case .Female: genderImageView.image = UIImage(named: "sqFemale") case .Unknown: genderImageView.image = nil } } } // 昵称 @IBOutlet weak var userNameLabel: UILabel! // 距离 @IBOutlet weak var distanceLabel: UILabel! // 宠物 @IBOutlet private var petImageViews: [UIImageView]! var petImagePaths: [String]? { didSet { if let images = petImagePaths { for i_imageView in petImageViews { if images.count >= i_imageView.tag { i_imageView.setImageWithURL(NSURL(string: images[i_imageView.tag - 1]), placeholderImage: UIImage(named: "placeholderLogo")) } else { i_imageView.image = nil } } } else { for oneImage in petImageViews { oneImage.image = nil } } } } @IBOutlet private weak var sepratorHeight: NSLayoutConstraint! @IBOutlet private weak var sepratorImageView: UIImageView! class var identifier: String { return "FindCatelogWhiteCellIdentifier" } override func awakeFromNib() { super.awakeFromNib() // Initialization code keeperAvatarImageView.roundCorner() sepratorHeight.constant = 1.0 / UIScreen.mainScreen().scale sepratorImageView.image = LCYCommon.sharedInstance.circleSepratorImage } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
aacbfdee765d79915d2cce6cf5fac57f
27.205607
148
0.537442
false
false
false
false
master-nevi/UPnAtom
refs/heads/master
Examples/ControlPointDemo_Swift/ControlPointDemo/Player.swift
mit
1
// // Player.swift // // Copyright (c) 2015 David Robles // // 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 UPnAtom private let _PlayerSharedInstance = Player() class Player { class var sharedInstance: Player { return _PlayerSharedInstance } var mediaServer: MediaServer1Device? var mediaRenderer: MediaRenderer1Device? { didSet { didSetRenderer(oldRenderer: oldValue, newRenderer: mediaRenderer) } } private(set) var playPauseButton: UIBarButtonItem! // TODO: Should ideally be a constant, see Github issue #10 private(set) var stopButton: UIBarButtonItem! // TODO: Should ideally be a constant, see Github issue #10 private var _position: Int = 0 private var _playlist: [ContentDirectory1Object]? private var _avTransportEventObserver: AnyObject? private var _playerState: PlayerState = PlayerState.Stopped { didSet { playerStateDidChange() } } private var _avTransportInstanceID = "0" enum PlayerState { case Unknown case Stopped case Playing case Paused } init() { playPauseButton = UIBarButtonItem(image: UIImage(named: "play_button"), style: .Plain, target: self, action: #selector(Player.playPauseButtonTapped(_:))) stopButton = UIBarButtonItem(image: UIImage(named: "stop_button"), style: .Plain, target: self, action: #selector(Player.stopButtonTapped(_:))) } func startPlayback(playlist: [ContentDirectory1Object], position: Int) { _playlist = playlist startPlayback(position: position) } func startPlayback(position position: Int) { _position = position if let item = _playlist?[position] as? ContentDirectory1VideoItem { let uri = item.resourceURL.absoluteString let instanceID = _avTransportInstanceID mediaRenderer?.avTransportService?.setAVTransportURI(instanceID: instanceID, currentURI: uri, currentURIMetadata: "", success: { () -> Void in print("URI set succeeded!") self.play({ () -> Void in print("Play command succeeded!") }, failure: { (error) -> Void in print("Play command failed: \(error)") }) }, failure: { (error) -> Void in print("URI set failed: \(error)") }) } } @objc private func playPauseButtonTapped(sender: AnyObject) { print("play/pause button tapped") switch _playerState { case .Playing: pause({ () -> Void in print("Pause command succeeded!") }, failure: { (error) -> Void in print("Pause command failed: \(error)") }) case .Paused, .Stopped: play({ () -> Void in print("Play command succeeded!") }, failure: { (error) -> Void in print("Play command failed: \(error)") }) default: print("Play/pause button cannot be used in this state.") } } @objc private func stopButtonTapped(sender: AnyObject) { print("stop button tapped") switch _playerState { case .Playing, .Paused: stop({ () -> Void in print("Stop command succeeded!") }, failure: { (error) -> Void in print("Stop command failed: \(error)") }) case .Stopped: print("Stop button cannot be used in this state.") default: print("Stop button cannot be used in this state.") } } private func didSetRenderer(oldRenderer oldRenderer: MediaRenderer1Device?, newRenderer: MediaRenderer1Device?) { if let avTransportEventObserver: AnyObject = _avTransportEventObserver { oldRenderer?.avTransportService?.removeEventObserver(avTransportEventObserver) } _avTransportEventObserver = newRenderer?.avTransportService?.addEventObserver(NSOperationQueue.currentQueue(), callBackBlock: { (event: UPnPEvent) -> Void in if let avTransportEvent = event as? AVTransport1Event, transportState = (avTransportEvent.instanceState["TransportState"] as? String)?.lowercaseString { print("\(event.service?.className) Event: \(avTransportEvent.instanceState)") print("transport state: \(transportState)") if transportState.rangeOfString("playing") != nil { self._playerState = .Playing } else if transportState.rangeOfString("paused") != nil { self._playerState = .Paused } else if transportState.rangeOfString("stopped") != nil { self._playerState = .Stopped } else { self._playerState = .Unknown } } }) } private func playerStateDidChange() { switch _playerState { case .Stopped, .Paused, .Unknown: playPauseButton.image = UIImage(named: "play_button") case .Playing: playPauseButton.image = UIImage(named: "pause_button") } } private func play(success: () -> Void, failure:(error: NSError) -> Void) { self.mediaRenderer?.avTransportService?.play(instanceID: _avTransportInstanceID, speed: "1", success: success, failure: failure) } private func pause(success: () -> Void, failure:(error: NSError) -> Void) { self.mediaRenderer?.avTransportService?.pause(instanceID: _avTransportInstanceID, success: success, failure: failure) } private func stop(success: () -> Void, failure:(error: NSError) -> Void) { self.mediaRenderer?.avTransportService?.stop(instanceID: _avTransportInstanceID, success: success, failure: failure) } }
b055035fbf68d042f2dac53da6416de2
40.270115
165
0.605069
false
false
false
false
goRestart/restart-backend-app
refs/heads/develop
Sources/Domain/Model/Game/Game.swift
gpl-3.0
1
import Foundation public struct Game { public let identifier: String public let title: String public let alternativeNames: [String] public let description: String public let images: [Image] public let company: GameCompany? public let platforms: [Platform] public let genres: [GameGenre] public let released: Date public init(identifier: String, title: String, alternativeNames: [String], description: String, images: [Image], company: GameCompany?, platforms: [Platform], genres: [GameGenre], released: Date) { self.identifier = identifier self.title = title self.alternativeNames = alternativeNames self.description = description self.images = images self.company = company self.platforms = platforms self.genres = genres self.released = released } }
a2e5815fa64b1c0333042f3ab3e712e4
27.885714
48
0.586548
false
false
false
false
tutsplus/iOSFromScratch-ShoppingList-2
refs/heads/master
Shopping List/EditItemViewController.swift
bsd-2-clause
1
// // EditItemViewController.swift // Shopping List // // Created by Bart Jacobs on 18/12/15. // Copyright © 2015 Envato Tuts+. All rights reserved. // import UIKit protocol EditItemViewControllerDelegate { func controller(controller: EditItemViewController, didUpdateItem item: Item) } class EditItemViewController: UIViewController { @IBOutlet var nameTextField: UITextField! @IBOutlet var priceTextField: UITextField! var item: Item! var delegate: EditItemViewControllerDelegate? // MARK: - // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Create Save Button navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "save:") // Populate Text Fields nameTextField.text = item.name priceTextField.text = "\(item.price)" } // MARK: - // MARK: Actions func save(sender: UIBarButtonItem) { if let name = nameTextField.text, let priceAsString = priceTextField.text, let price = Float(priceAsString) { // Update Item item.name = name item.price = price // Notify Delegate delegate?.controller(self, didUpdateItem: item) // Pop View Controller navigationController?.popViewControllerAnimated(true) } } }
101d75551248c11da641eccebac39b78
26.358491
118
0.626897
false
false
false
false
vanyaland/Tagger
refs/heads/master
Tagger/Sources/Common/Helpers/WebService/Base/HttpApiClient+MultipartFormData.swift
mit
1
/** * Copyright (c) 2016 Ivan Magda * * 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 // MARK: Typealiases /// - parameter data: Data to uploaded /// - parameter name: The optional field name to be used when uploading files. If you supply paths, you must supply filePathKey, too. /// - parameter fileName: Name of the uploading file typealias MultipartData = (data: Data, name: String, fileName: String) // MARK: - HttpApiClient (multipart/form-data) extension HttpApiClient { /// Creates body of the multipart/form-data request /// /// - parameter parameters: The optional dictionary containing keys and values to be passed to web service /// - parameter files: An optional array containing multipart/form-data parts /// - parameter boundary: The multipart/form-data boundary /// /// - returns: The NSData of the body of the request func createMultipartBody(params parameters: HttpMethodParams?, files: [MultipartData]?, boundary: String) -> Data { let body = NSMutableData() parameters?.forEach { (key, value) in body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.appendString("\(value)\r\n") } files?.forEach { body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition:form-data; name=\"\($0.name)\"; filename=\"\($0.fileName)\"\r\n") body.appendString("Content-Type: \($0.data.mimeType)\r\n\r\n") body.append($0.data) body.appendString("\r\n") } body.appendString("--\(boundary)--\r\n") return body as Data } /// Create boundary string for multipart/form-data request /// /// - returns: The boundary string that consists of "Boundary-" followed by a UUID string. func generateBoundaryString() -> String { return "Boundary-\(UUID().uuidString)" } } // MARK: - NSMutableData+AppendString - extension NSMutableData { /// Append string to NSMutableData /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to NSData, and then add that data to the NSMutableData, this wraps it in a nice convenient little extension to NSMutableData. This converts using UTF-8. /// /// - parameter string: The string to be added to the `NSMutableData`. func appendString(_ string: String) { let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true) append(data!) } }
50772ae19d85c2b211f3252785252522
39.956044
243
0.668098
false
false
false
false
shu223/watchOS-2-Sampler
refs/heads/master
watchOS2Sampler WatchKit Extension/PickerStylesInterfaceController.swift
mit
1
// // PickerStylesInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/12. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class PickerStylesInterfaceController: WKInterfaceController { @IBOutlet weak var listPicker: WKInterfacePicker! @IBOutlet weak var stackPicker: WKInterfacePicker! @IBOutlet weak var sequencePicker: WKInterfacePicker! var pickerItems: [WKPickerItem]! = [] override func awake(withContext context: Any?) { super.awake(withContext: context) for i in 1...10 { let pickerItem = WKPickerItem() let imageName = "m\(i)" let image = WKImage(imageName: imageName) // Text to show when the item is being displayed in a picker with the 'List' style. pickerItem.title = imageName // Caption to show for the item when focus style includes a caption callout. pickerItem.caption = imageName // An accessory image to show next to the title in a picker with the 'List' style. // Note that the image will be scaled and centered to fit within an 13×13pt rect. pickerItem.accessoryImage = image // A custom image to show for the item, used instead of the title + accessory // image when more flexibility is needed, or when displaying in the stack or // sequence style. The image will be scaled and centered to fit within the // picker's bounds or item row bounds. pickerItem.contentImage = image pickerItems.append(pickerItem) // print("\(pickerItems)") } } override func willActivate() { super.willActivate() listPicker.setItems(pickerItems) sequencePicker.setItems(pickerItems) stackPicker.setItems(pickerItems) } override func didDeactivate() { super.didDeactivate() } }
584b9bbc1c7825f32daf40927d9af10c
31.936508
95
0.624096
false
false
false
false
zalando/ModularDemo
refs/heads/master
IPLookupUI/IPLookupUI App/MyIPTestService.swift
bsd-2-clause
1
// // MyIPTestService.swift // IPLookupUI App // // Created by Oliver Eikemeier on 26.09.15. // Copyright © 2015 Zalando SE. All rights reserved. // import Foundation import ZContainer import IPLookupUI class MyIPTestService: IPLookupUIService { // MARK: - Shared Instance private static let sharedInstance = MyIPTestService() static func sharedService() -> MyIPTestService { return MyIPTestService.sharedInstance } // MARK: - Result Type enum ResultType { case IPv4, IPv6, Timeout, Immediate, Alternating } var resultType: ResultType private init(resultType: ResultType = .Immediate) { self.resultType = resultType } // MARK: - Lookup Simulation private let completionQueue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0) private func complete(after delta: NSTimeInterval = 0.0, IP: String? = nil, error: ErrorType? = nil, completionHandler: (IP: String?, error: ErrorType?) -> Void) { let when: dispatch_time_t if delta > 0 { let offset = Int64(delta * Double(NSEC_PER_SEC)) when = dispatch_time(DISPATCH_TIME_NOW, offset) } else { when = DISPATCH_TIME_NOW } dispatch_after(when, completionQueue) { completionHandler(IP: IP, error: error) } } private var timeoutResult = true func lookupIP(completionHandler: (IP: String?, error: ErrorType?) -> Void) { switch resultType { case .IPv4: complete(after: 2.0, IP: "69.89.31.226", completionHandler: completionHandler) case .IPv6: complete(after: 2.0, IP: "2001:0db8:85a3:08d3:1319:8a2e:0370:7344", completionHandler: completionHandler) case .Timeout: complete(after: 5.0, error: NSURLError.TimedOut, completionHandler: completionHandler) case .Immediate: complete(IP: "127.0.0.1", completionHandler: completionHandler) case .Alternating: if timeoutResult { complete(after: 2.0, error: NSURLError.TimedOut, completionHandler: completionHandler) } else { complete(IP: "127.0.0.1", completionHandler: completionHandler) } timeoutResult = !timeoutResult } } }
afa4b35ae1210ff83c9bd60b5d5e443c
30.644737
167
0.602495
false
true
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Display information/Display grid/DisplayGridViewController.swift
apache-2.0
1
// // Copyright 2017 Esri. // // 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 UIKit import ArcGIS class DisplayGridViewController: UIViewController { @IBOutlet weak var mapView: AGSMapView! override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = [ "DisplayGridViewController", "DisplayGridSettingsViewController", "OptionsTableViewController", "ColorPickerViewController" ] // Assign map to the map view. mapView.map = AGSMap(basemapStyle: .arcGISImageryStandard) // Set viewpoint. let center = AGSPoint(x: -7702852.905619, y: 6217972.345771, spatialReference: .webMercator()) mapView.setViewpoint(AGSViewpoint(center: center, scale: 23227)) // Add lat long grid. mapView.grid = AGSLatitudeLongitudeGrid() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController, let controller = navController.viewControllers.first as? DisplayGridSettingsViewController { controller.mapView = mapView controller.preferredContentSize = { let height: CGFloat if traitCollection.horizontalSizeClass == .regular, traitCollection.verticalSizeClass == .regular { height = 350 } else { height = 250 } return CGSize(width: 375, height: height) }() navController.presentationController?.delegate = self } } } extension DisplayGridViewController: UIAdaptivePresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
26eecc6ce00fed6bb91609bc90ac188d
38.075758
142
0.661497
false
false
false
false
na4lapy/na4lapy-ios
refs/heads/master
Na4Łapy/Model/Photo.swift
apache-2.0
1
// // Photo.swift // Na4Łapy // // Created by Andrzej Butkiewicz on 06.06.2016. // Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved. // import Foundation import UIKit class Photo { let id: Int let url: URL var author: String? var image: UIImage? var downloaded: Bool = false var profile: Bool = false init?(dictionary: [String:AnyObject]) { guard let id = dictionary[JsonAttr.id] as? Int, let fileName = dictionary[JsonAttr.fileName] as? String, let url = URL(string: baseUrl + EndPoint.files + fileName) else { log.error(Err.noIdOrName.desc()) return nil } self.id = id self.url = url self.image = UIImage(named: "Placeholder") if let author = dictionary[JsonAttr.author] as? String { self.author = author } if let isProfile = dictionary[JsonAttr.profile] as? Bool { self.profile = isProfile } } /** Asynchroniczne pobieranie obrazka */ func download(_ success: (() -> Void)? = nil) { if self.downloaded { log.debug("Zdjęcie zostało już wcześniej pobrane.") success?() return } log.debug("Pobieram zdjęcie... \(self.url.absoluteString)") Request.getImageData(self.url, success: { (image) in self.image = image self.downloaded = true success?() }, failure: { (error) in log.error("Błąd: \(error.localizedDescription) dla urla: \(self.url.absoluteString)") } ) } }
1757cb8d2e3db3d9087b2a6e73609fae
25.4
101
0.537296
false
false
false
false
wuhduhren/Mr-Ride-iOS
refs/heads/master
Mr-Ride-iOS/Model/MapData/MapDataRouter.swift
mit
1
// // MapDataRouter.swift // Mr-Ride-iOS // // Created by Eph on 2016/6/13. // Copyright © 2016年 AppWorks School WuDuhRen. All rights reserved. // Reference: YBRouter.swift Created by 許郁棋 on 2016/4/27. // import Alamofire import JWT enum MapDataRouter { case GetPublicToilets case GetRiverSideToilets case GetYoubike } // MARK: - URLRequestConvertible extension MapDataRouter: URLRequestConvertible { var method: Alamofire.Method { switch self { case .GetRiverSideToilets: return .GET case .GetYoubike: return .GET case .GetPublicToilets: return .GET } } var url: NSURL { switch self { case .GetRiverSideToilets: return NSURL(string: "http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=fe49c753-9358-49dd-8235-1fcadf5bfd3f")! case .GetYoubike: return NSURL(string: "http://data.taipei/youbike")! case .GetPublicToilets: return NSURL(string: "http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=008ed7cf-2340-4bc4-89b0-e258a5573be2")! } } var URLRequest: NSMutableURLRequest { let URLRequest = NSMutableURLRequest(URL: url) URLRequest.HTTPMethod = method.rawValue return URLRequest } }
a2b6c580a3f95818f0b9ae4436cd998a
24.327273
172
0.634602
false
false
false
false
jindulys/ChainPageCollectionView
refs/heads/master
Sources/EdgeCardLayout.swift
mit
1
/** * Copyright (c) 2017 Yansong Li * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit /// The layout that can place a card at the left edge of screen. public class EdgeCardLayout: UICollectionViewFlowLayout { fileprivate var lastCollectionViewSize: CGSize = CGSize.zero public required init?(coder aDecoder: NSCoder) { fatalError() } override init() { super.init() scrollDirection = .horizontal minimumLineSpacing = 25 } public override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) guard let collectionView = collectionView else { return } if collectionView.bounds.size != lastCollectionViewSize { configureInset() lastCollectionViewSize = collectionView.bounds.size } } public override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = collectionView else { return proposedContentOffset } let proposedRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height) guard var layoutAttributes = layoutAttributesForElements(in: proposedRect) else { return proposedContentOffset } layoutAttributes = layoutAttributes.sorted { $0.frame.origin.x < $1.frame.origin.x } let leftMostAttribute = layoutAttributes[0] if leftMostAttribute.frame.origin.x > proposedContentOffset.x { return CGPoint(x: leftMostAttribute.frame.origin.x - minimumLineSpacing, y: proposedContentOffset.y) } if velocity.x > 0 { if fabs(leftMostAttribute.frame.origin.x - proposedContentOffset.x) > (itemSize.width / 2) || velocity.x > 0.3 { return CGPoint(x: leftMostAttribute.frame.maxX, y: proposedContentOffset.y) } else { return CGPoint(x: leftMostAttribute.frame.origin.x - minimumLineSpacing, y: proposedContentOffset.y) } } if velocity.x < 0 { if fabs(leftMostAttribute.frame.origin.x - proposedContentOffset.x) <= (itemSize.width / 2) || velocity.x < -0.3 { return CGPoint(x: leftMostAttribute.frame.origin.x - minimumLineSpacing, y: proposedContentOffset.y) } else { return CGPoint(x: leftMostAttribute.frame.maxX, y: proposedContentOffset.y) } } return proposedContentOffset } } // MARK: helpers extension EdgeCardLayout { fileprivate func configureInset() -> Void { guard let collectionView = collectionView else { return } let inset = minimumLineSpacing collectionView.contentInset = UIEdgeInsetsMake(0, inset, 0, inset) collectionView.contentOffset = CGPoint(x: -inset, y: 0) } }
acc6cc3afec51c58c683c9baad492822
38.119658
99
0.698711
false
false
false
false
igroomgrim/swift101
refs/heads/master
Swift101_Playground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit // Day 92 - Import your class into XCODE 7 Playground /* let userAddress = Address(buildingName: "Shanghai Tower", buildingNumber: "BD01", street: "Shanghai Road") userAddress.buildingName userAddress.buildingNumber userAddress.street userAddress.displayDetail() */ // Day 91 - Strings in Swift 2 /* var letters: [Character] = ["A", "R", "S", "E", "N", "A", "L"] var string: String = String(letters) print(letters.count) print(string) print(string.characters.count) let registeredTrademark: Character = "\u{00AE}" string.append(registeredTrademark) print(string.characters.count) print(string.characters.last!) print(string.characters.first!) string.characters.contains("S") */ // Day 90 - UIKit on playground /* let maView = MaView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) maView.backgroundColor = UIColor.blueColor() maView let testButton = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 44)) testButton.backgroundColor = UIColor.greenColor() testButton let maButton = MaButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) maButton.backgroundColor = UIColor.greenColor() maButton.layer.cornerRadius = 4 maButton */ // Day 89 - Sets var characters = Set<Character>() characters.insert("R") characters.insert("O") characters.insert("C") characters.insert("K") characters var pointSet: Set<Int> = [1,2,3,4,5,6,7,8,9] for point in pointSet { print("\(point)") } for point in pointSet.sort() { print("\(point)") } var setOne: Set<Int> = [4,5,6,7,8,8] var setTwo: Set<Int> = [1,2,3,4,5] setOne.intersect(setTwo) setOne.subtract(setTwo)
ed14ee09cf91b9dd95a5bf273bc70e9c
22.782609
106
0.714808
false
false
false
false
HJliu1123/LearningNotes-LHJ
refs/heads/master
April/Xbook/Xbook/pushNewBook/Controller/HJPhotoPickerController.swift
apache-2.0
1
// // HJPhotoPickerController.swift // Xbook // // Created by liuhj on 16/1/22. // Copyright © 2016年 liuhj. All rights reserved. // import UIKit protocol HJPhotoPickerDelegate { func getImageFromPicker(image:UIImage) } class HJPhotoPickerController: UIViewController ,UIImagePickerControllerDelegate, UINavigationControllerDelegate{ var alert : UIAlertController? var picker : UIImagePickerController! var delegate : HJPhotoPickerDelegate! override func viewDidLoad() { super.viewDidLoad() } init() { super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .OverFullScreen self.view.backgroundColor = UIColor.clearColor() self.picker = UIImagePickerController() self.picker.allowsEditing = false self.picker.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(animated: Bool) { if (self.alert == nil) { self.alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) self.alert?.addAction(UIAlertAction(title: "从相册选择", style: .Default, handler: { (action) -> Void in self.localPhoto() })) self.alert?.addAction(UIAlertAction(title: "打开相机", style: .Default, handler: { (action) -> Void in self.takePhoto() })) self.alert?.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: { (action) -> Void in })) self.presentViewController(self.alert!, animated: true, completion: { () -> Void in }) } } /* 打开相机 */ func takePhoto() { //判断该机型是否有相机功能 if (UIImagePickerController.isSourceTypeAvailable(.Camera)) { self.picker?.sourceType = .Camera self.presentViewController(self.picker!, animated: true, completion: { () -> Void in }) } else { let alertView = UIAlertController(title: "无相机", message: nil, preferredStyle: .Alert) alertView.addAction(UIAlertAction(title: "关闭", style: .Cancel, handler: { (ACTION) -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in }) })) self.presentViewController(alertView, animated: true, completion: { () -> Void in }) } } /* 打开本地相册 */ func localPhoto() { self.picker?.sourceType = .PhotoLibrary self.presentViewController(self.picker, animated: true) { () -> Void in } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.picker?.dismissViewControllerAnimated(true) { () -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.picker?.dismissViewControllerAnimated(true){ () -> Void in self.dismissViewControllerAnimated(true, completion: { () -> Void in self.delegate.getImageFromPicker(image) }) } } }
9f49e1a51a742b7babfac2ef746990d7
26.107914
123
0.550159
false
false
false
false
zhangjk4859/NextStep
refs/heads/master
代码实现/测试区域/基本语法/基本语法/struct.swift
gpl-3.0
1
// // struct.swift // 基本语法 // // Created by 张俊凯 on 2017/1/13. // Copyright © 2017年 张俊凯. All rights reserved. // import Foundation //class Person { // var residence: Residence? //} // //// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组 //class Residence { // var rooms = [Room]() // var numberOfRooms: Int { // return rooms.count // } // subscript(i: Int) -> Room { // return rooms[i] // } // func printNumberOfRooms() { // print("房间号为 \(numberOfRooms)") // } // var address: Address? //} // //// Room 定义一个name属性和一个设定room名的初始化器 //class Room { // let name: String // init(name: String) { self.name = name } //} // //// 模型中的最终类叫做Address //class Address { // var buildingName: String? // var buildingNumber: String? // var street: String? // func buildingIdentifier() -> String? { // if (buildingName != nil) { // return buildingName // } else if (buildingNumber != nil) { // return buildingNumber // } else { // return nil // } // } //} // //let john = Person() // // //if ((john.residence?.printNumberOfRooms()) != nil) { // print("输出房间号") //} else { // print("无法输出房间号") //} //class Person { // var residence: Residence? //} // //// 定义了一个变量 rooms,它被初始化为一个Room[]类型的空数组 //class Residence { // var rooms = [Room]() // var numberOfRooms: Int { // return rooms.count // } // subscript(i: Int) -> Room { // return rooms[i] // } // func printNumberOfRooms() { // print("房间号为 \(numberOfRooms)") // } // var address: Address? //} // //// Room 定义一个name属性和一个设定room名的初始化器 //class Room { // let name: String // init(name: String) { self.name = name } //} // //// 模型中的最终类叫做Address //class Address { // var buildingName: String? // var buildingNumber: String? // var street: String? // func buildingIdentifier() -> String? { // if (buildingName != nil) { // return buildingName // } else if (buildingNumber != nil) { // return buildingNumber // } else { // return nil // } // } //} //class Person { // var residence: Residence? //} // //class Residence { // var numberOfRooms = 1 //} // //let john = Person() // //// 链接可选residence?属性,如果residence存在则取回numberOfRooms的值 //if let roomCount = john.residence?.numberOfRooms { // print("John 的房间号为 \(roomCount)。") //} else { // print("不能查看房间号") //} // //class Person { // var residence: Residence? //} // //class Residence { // var numberOfRooms = 1 //} // //let john = Person() // ////将导致运行时错误 //let roomCount = john.residence?.numberOfRooms // //print(roomCount) //var counter = 0; // 引用计数器 //class BaseClass { // init() { // counter += 1; // } // // deinit { // counter -= 1; // } //} // //var show: BaseClass? = BaseClass() // //print(counter) //print(counter) //var counter = 0; // 引用计数器 //class BaseClass { // init() { // counter += 1; // } // deinit { // counter -= 1; // } //} // //var show: BaseClass? = BaseClass() //print(counter) //show = nil //print(counter) //struct StudRecord { // let stname: String // // init!(stname: String) { // if stname.isEmpty {return nil } // self.stname = stname // } //} // //let stmark = StudRecord(stname: "Runoob") //if let name = stmark { // print("指定了学生名") //} // //let blankname = StudRecord(stname: "") //if blankname == nil { // print("学生名为空") //} //class Planet { // var name: String // // init(name: String) { // self.name = name // } // // convenience init() { // self.init(name: "[No Planets]") // } //} //let plName = Planet(name: "Mercury") //print("行星的名字是: \(plName.name)") // //let noplName = Planet() //print("没有这个名字的行星: \(noplName.name)") // //class planets: Planet { // var count: Int // // init(name: String, count: Int) { // self.count = count // super.init(name: name) // } // // override convenience init(name: String) { // self.init(name: name, count: 1) // } //} //class StudRecord { // let studname: String! // init?(studname: String) { // self.studname = studname // if studname.isEmpty { return nil } // } //} //if let stname = StudRecord(studname: "失败构造器") { // print("模块为 \(stname.studname)") //} //enum TemperatureUnit { // // 开尔文,摄氏,华氏 // case Kelvin, Celsius, Fahrenheit // init?(symbol: Character) { // switch symbol { // case "K": // self = .Kelvin // case "C": // self = .Celsius // case "F": // self = .Fahrenheit // default: // return nil // } // } //} // // //let fahrenheitUnit = TemperatureUnit(symbol: "F") //if fahrenheitUnit != nil { // print("这是一个已定义的温度单位,所以初始化成功。") //} // //let unknownUnit = TemperatureUnit(symbol: "X") //if unknownUnit == nil { // print("这不是一个已定义的温度单位,所以初始化失败。") //} //struct Animal { // let species: String // init?(species: String) { // if species.isEmpty { return nil } // self.species = species // } //} // ////通过该可失败构造器来构建一个Animal的对象,并检查其构建过程是否成功 //// someCreature 的类型是 Animal? 而不是 Animal //let someCreature = Animal(species: "长颈鹿") // //// 打印 "动物初始化为长颈鹿" //if let giraffe = someCreature { // print("动物初始化为\(giraffe.species)") //} //class SuperClass { // var corners = 4 // var description: String { // return "\(corners) 边" // } //} //let rectangle = SuperClass() //print("矩形: \(rectangle.description)") // //class SubClass: SuperClass { // override init() { //重载构造器 // super.init() // corners = 5 // } //} // //let subClass = SubClass() //print("五角型: \(subClass.description)") //class mainClass { // var no1 : Int // 局部存储变量 // init(no1 : Int) { // self.no1 = no1 // 初始化 // } //} // //class subClass : mainClass { // var no2 : Int // init(no1 : Int, no2 : Int) { // self.no2 = no2 // super.init(no1:no1) // } // // 便利方法只需要一个参数 // override convenience init(no1: Int) { // self.init(no1:no1, no2:0) // } //} //let res = mainClass(no1: 20) //let res2 = subClass(no1: 30, no2: 50) // //print("res 为: \(res.no1)") //print("res2 为: \(res2.no1)") //print("res2 为: \(res2.no2)") //class mainClass { // var no1 : Int // 局部存储变量 // init(no1 : Int) { // self.no1 = no1 // 初始化 // } //} //class subClass : mainClass { // var no2 : Int // 新的子类存储变量 // init(no1 : Int, no2 : Int) { // self.no2 = no2 // 初始化 // super.init(no1:no1) // 初始化超类 // } //} // //let res = mainClass(no1: 10) //let res2 = subClass(no1: 10, no2: 20) // //print("res 为: \(res.no1)") //print("res2 为: \(res2.no1)") //print("res2 为: \(res2.no2)") ////在init方法里做事情,节省代码 //struct Size { // var width = 0.0, height = 0.0 //} //struct Point { // var x = 0.0, y = 0.0 //} // //struct Rect { // var origin = Point() // var size = Size() // init() {} // init(origin: Point, size: Size) { // self.origin = origin // self.size = size // } // init(center: Point, size: Size) { // let originX = center.x - (size.width / 2) // let originY = center.y - (size.height / 2) // self.init(origin: Point(x: originX, y: originY), size: size) // } //} // // //// origin和size属性都使用定义时的默认值Point(x: 0.0, y: 0.0)和Size(width: 0.0, height: 0.0): //let basicRect = Rect() //print("Size 结构体初始值: \(basicRect.size.width, basicRect.size.height) ") //print("Rect 结构体初始值: \(basicRect.origin.x, basicRect.origin.y) ") // //// 将origin和size的参数值赋给对应的存储型属性 //let originRect = Rect(origin: Point(x: 2.0, y: 2.0), // size: Size(width: 5.0, height: 5.0)) // //print("Size 结构体初始值: \(originRect.size.width, originRect.size.height) ") //print("Rect 结构体初始值: \(originRect.origin.x, originRect.origin.y) ") // // ////先通过center和size的值计算出origin的坐标。 ////然后再调用(或代理给)init(origin:size:)构造器来将新的origin和size值赋值到对应的属性中 //let centerRect = Rect(center: Point(x: 4.0, y: 4.0), // size: Size(width: 3.0, height: 3.0)) // //print("Size 结构体初始值: \(centerRect.size.width, centerRect.size.height) ") //print("Rect 结构体初始值: \(centerRect.origin.x, centerRect.origin.y) ") //struct Rectangle { // var length = 100.0, breadth = 200.0 //} //let area = Rectangle(length: 24.0, breadth: 32.0) // //print("矩形的面积: \(area.length)") //print("矩形的面积: \(area.breadth)") //class ShoppingListItem { // var name: String? // var quantity = 1 // var purchased = false //} //var item = ShoppingListItem() // // //print("名字为: \(item.name)") //print("数理为: \(item.quantity)") //print("是否付款: \(item.purchased)") //struct Rectangle { // let length: Double? // // init(frombreadth breadth: Double) { // length = breadth * 10 // } // // init(frombre bre: Double) { // length = bre * 30 // } // // init(_ area: Double) { // length = area // } //} // //let rectarea = Rectangle(180.0) //print("面积为:\(rectarea.length)") // //let rearea = Rectangle(370.0) //print("面积为:\(rearea.length)") // //let recarea = Rectangle(110.0) //print("面积为:\(recarea.length)") //struct Rectangle { // var length: Double? // // init(frombreadth breadth: Double) { // length = breadth * 10 // } // // init(frombre bre: Double) { // length = bre * 30 // } // // init(_ area: Double) { // length = area // } //} // //let rectarea = Rectangle(180.0) //print("面积为:\(rectarea.length)") // //let rearea = Rectangle(370.0) //print("面积为:\(rearea.length)") // //let recarea = Rectangle(110.0) //print("面积为:\(recarea.length)") //struct Rectangle { // var length: Double // // init(frombreadth breadth: Double) { // length = breadth * 10 // } // // init(frombre bre: Double) { // length = bre * 30 // } // //不提供外部名字 // init(_ area: Double) { // length = area // } //} // //// 调用不提供外部名字 //let rectarea = Rectangle(180.0) //print("面积为: \(rectarea.length)") // //// 调用不提供外部名字 //let rearea = Rectangle(370.0) //print("面积为: \(rearea.length)") // //// 调用不提供外部名字 //let recarea = Rectangle(110.0) //print("面积为: \(recarea.length)") //struct Color { // let red, green, blue: Double // init(red: Double, green: Double, blue: Double) { // self.red = red // self.green = green // self.blue = blue // } // init(white: Double) { // red = white // green = white // blue = white // } //} // //// 创建一个新的Color实例,通过三种颜色的外部参数名来传值,并调用构造器 //let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) // //print("red 值为: \(magenta.red)") //print("green 值为: \(magenta.green)") //print("blue 值为: \(magenta.blue)") // //// 创建一个新的Color实例,通过三种颜色的外部参数名来传值,并调用构造器 //let halfGray = Color(white: 0.5) //print("red 值为: \(halfGray.red)") //print("green 值为: \(halfGray.green)") //print("blue 值为: \(halfGray.blue)") //struct Rectangle { // var length: Double // var breadth: Double // var area: Double // // init(fromLength length: Double, fromBreadth breadth: Double) { // self.length = length // self.breadth = breadth // self.area = length * breadth // } // // init(fromLeng leng: Double, fromBread bread: Double) { // self.length = leng // self.breadth = bread // self.area = leng * bread // } //} // //let ar = Rectangle(fromLength: 6, fromBreadth: 12) //print("面积为: \(ar.area)") // //let are = Rectangle(fromLeng: 36, fromBread: 12) //print("面积为: \(are.area)") //struct rectangle { // // 设置默认值 // var length = 6 // var breadth = 12 //} //var area = rectangle() //print("矩形的面积为 \(area.length*area.breadth)") //struct rectangle { // var length: Double // var breadth: Double // init() { // length = 6 // breadth = 12 // } //} //var area = rectangle() //print("矩形面积为 \(area.length*area.breadth)")
327abe97fec623f485607fce9959fbfe
20.056738
80
0.55128
false
false
false
false
auth0/JWTDecode.swift
refs/heads/master
JWTDecodeTests/JWTDecodeSpec.swift
mit
1
import Quick import Nimble import JWTDecode import Foundation class JWTDecodeSpec: QuickSpec { override func spec() { describe("decode") { it("should tell a jwt is expired") { expect(expiredJWT().expired).to(beTruthy()) } it("should tell a jwt is not expired") { expect(nonExpiredJWT().expired).to(beFalsy()) } it("should tell a jwt is expired with a close enough timestamp") { expect(jwtThatExpiresAt(date: Date()).expired).to(beTruthy()) } it("should obtain payload") { let jwt = jwt(withBody: ["sub": "myid", "name": "Shawarma Monk"]) let payload = jwt.body as! [String: String] expect(payload).to(equal(["sub": "myid", "name": "Shawarma Monk"])) } it("should return original jwt string representation") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb20uc29td2hlcmUuZmFyLmJleW9uZDphcGkiLCJpc3MiOiJhdXRoMCIsInVzZXJfcm9sZSI6ImFkbWluIn0.sS84motSLj9HNTgrCPcAjgZIQ99jXNN7_W9fEIIfxz0" let jwt = try! decode(jwt: jwtString) expect(jwt.string).to(equal(jwtString)) } it("should return expire date") { expect(expiredJWT().expiresAt).toNot(beNil()) } it("should decode valid jwt") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjb20uc29td2hlcmUuZmFyLmJleW9uZDphcGkiLCJpc3MiOiJhdXRoMCIsInVzZXJfcm9sZSI6ImFkbWluIn0.sS84motSLj9HNTgrCPcAjgZIQ99jXNN7_W9fEIIfxz0" expect(try! decode(jwt: jwtString)).toNot(beNil()) } it("should decode valid jwt with empty json body") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.Et9HFtf9R3GEMA0IICOfFMVXY7kkTX1wr4qCyhIf58U" expect(try! decode(jwt: jwtString)).toNot(beNil()) } it("should raise exception with invalid base64 encoding") { let invalidChar = "%" let jwtString = "\(invalidChar).BODY.SIGNATURE" expect { try decode(jwt: jwtString) } .to(throwError { (error: Error) in expect(error).to(beJWTDecodeError(.invalidBase64URL(invalidChar))) }) } it("should raise exception with invalid json in jwt") { let jwtString = "HEADER.BODY.SIGNATURE" expect { try decode(jwt: jwtString) } .to(throwError { (error: Error) in expect(error).to(beJWTDecodeError(.invalidJSON("HEADER"))) }) } it("should raise exception with missing parts") { let jwtString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWIifQ" expect { try decode(jwt: jwtString) } .to(throwError { (error: Error) in expect(error).to(beJWTDecodeError(.invalidPartCount(jwtString, 2))) }) } } describe("jwt parts") { let sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWIifQ.xXcD7WOvUDHJ94E6aVHYgXdsJHLl2oW7ZXm4QpVvXnY") it("should return header") { expect(sut.header as? [String: String]).to(equal(["alg": "HS256", "typ": "JWT"])) } it("should return body") { expect(sut.body as? [String: String]).to(equal(["sub": "sub"])) } it("should return signature") { expect(sut.signature).to(equal("xXcD7WOvUDHJ94E6aVHYgXdsJHLl2oW7ZXm4QpVvXnY")) } } describe("claims") { var sut: JWT! describe("expiresAt claim") { it("should handle expired jwt") { sut = expiredJWT() expect(sut.expiresAt).toNot(beNil()) expect(sut.expired).to(beTruthy()) } it("should handle non-expired jwt") { sut = nonExpiredJWT() expect(sut.expiresAt).toNot(beNil()) expect(sut.expired).to(beFalsy()) } it("should handle jwt without expiresAt claim") { sut = jwt(withBody: ["sub": UUID().uuidString]) expect(sut.expiresAt).to(beNil()) expect(sut.expired).to(beFalsy()) } } describe("registered claims") { let sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tIiwic3ViIjoiYXV0aDB8MTAxMDEwMTAxMCIsImF1ZCI6Imh0dHBzOi8vc2FtcGxlcy5hdXRoMC5jb20iLCJleHAiOjEzNzI2NzQzMzYsImlhdCI6MTM3MjYzODMzNiwianRpIjoicXdlcnR5MTIzNDU2IiwibmJmIjoxMzcyNjM4MzM2fQ.LvF9wSheCB5xarpydmurWgi9NOZkdES5AbNb_UWk9Ew") it("should return issuer") { expect(sut.issuer).to(equal("https://samples.auth0.com")) } it("should return subject") { expect(sut.subject).to(equal("auth0|1010101010")) } it("should return single audience") { expect(sut.audience).to(equal(["https://samples.auth0.com"])) } context("multiple audiences") { let sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiaHR0cHM6Ly9zYW1wbGVzLmF1dGgwLmNvbSIsImh0dHBzOi8vYXBpLnNhbXBsZXMuYXV0aDAuY29tIl19.cfWFPuJbQ7NToa-BjHgHD1tHn3P2tOP5wTQaZc1qg6M") it("should return all audiences") { expect(sut.audience).to(equal(["https://samples.auth0.com", "https://api.samples.auth0.com"])) } } it("should return issued at") { expect(sut.issuedAt).to(equal(Date(timeIntervalSince1970: 1372638336))) } it("should return not before") { expect(sut.notBefore).to(equal(Date(timeIntervalSince1970: 1372638336))) } it("should return jwt id") { expect(sut.identifier).to(equal("qwerty123456")) } } describe("custom claim") { beforeEach { sut = jwt(withBody: ["sub": UUID().uuidString, "custom_string_claim": "Shawarma Friday!", "custom_integer_claim": 10, "custom_double_claim": 3.4, "custom_double_string_claim": "1.3", "custom_true_boolean_claim": true, "custom_false_boolean_claim": false]) } it("should return claim by name") { let claim = sut.claim(name: "custom_string_claim") expect(claim.rawValue).toNot(beNil()) } it("should return string claim") { let claim = sut["custom_string_claim"] expect(claim.string) == "Shawarma Friday!" expect(claim.array) == ["Shawarma Friday!"] expect(claim.integer).to(beNil()) expect(claim.double).to(beNil()) expect(claim.date).to(beNil()) expect(claim.boolean).to(beNil()) } it("should return integer claim") { let claim = sut["custom_integer_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer) == 10 expect(claim.double) == 10.0 expect(claim.date) == Date(timeIntervalSince1970: 10) expect(claim.boolean).to(beNil()) } it("should return double claim") { let claim = sut["custom_double_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer) == 3 expect(claim.double) == 3.4 expect(claim.date) == Date(timeIntervalSince1970: 3.4) expect(claim.boolean).to(beNil()) } it("should return double as string claim") { let claim = sut["custom_double_string_claim"] expect(claim.string) == "1.3" expect(claim.array) == ["1.3"] expect(claim.integer).to(beNil()) expect(claim.double) == 1.3 expect(claim.date) == Date(timeIntervalSince1970: 1.3) expect(claim.boolean).to(beNil()) } it("should return true boolean claim") { let claim = sut["custom_true_boolean_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer).to(beNil()) expect(claim.double).to(beNil()) expect(claim.date).to(beNil()) expect(claim.boolean) == true } it("should return false boolean claim") { let claim = sut["custom_false_boolean_claim"] expect(claim.string).to(beNil()) expect(claim.array).to(beNil()) expect(claim.integer).to(beNil()) expect(claim.double).to(beNil()) expect(claim.date).to(beNil()) expect(claim.boolean) == false } it("should return no value when claim is not present") { let unknownClaim = sut["missing_claim"] expect(unknownClaim.array).to(beNil()) expect(unknownClaim.string).to(beNil()) expect(unknownClaim.integer).to(beNil()) expect(unknownClaim.double).to(beNil()) expect(unknownClaim.date).to(beNil()) expect(unknownClaim.boolean).to(beNil()) } context("raw claim") { var sut: JWT! beforeEach { sut = try! decode(jwt: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tIiwic3ViIjoiYXV0aDB8MTAxMDEwMTAxMCIsImF1ZCI6Imh0dHBzOi8vc2FtcGxlcy5hdXRoMC5jb20iLCJleHAiOjEzNzI2NzQzMzYsImlhdCI6MTM3MjYzODMzNiwianRpIjoicXdlcnR5MTIzNDU2IiwibmJmIjoxMzcyNjM4MzM2LCJlbWFpbCI6InVzZXJAaG9zdC5jb20iLCJjdXN0b20iOlsxLDIsM119.JeMRyHLkcoiqGxd958B6PABKNvhOhIgw-kbjecmhR_E") } it("should return email") { expect(sut["email"].string) == "user@host.com" } it("should return array") { expect(sut["custom"].rawValue as? [Int]).toNot(beNil()) } } } } } } public func beJWTDecodeError(_ code: JWTDecodeError) -> Predicate<Error> { return Predicate<Error>.define("be jwt decode error <\(code)>") { expression, failureMessage -> PredicateResult in guard let actual = try expression.evaluate() as? JWTDecodeError else { return PredicateResult(status: .doesNotMatch, message: failureMessage) } return PredicateResult(bool: actual == code, message: failureMessage) } } extension JWTDecodeError: Equatable {} public func ==(lhs: JWTDecodeError, rhs: JWTDecodeError) -> Bool { return lhs.localizedDescription == rhs.localizedDescription && lhs.errorDescription == rhs.errorDescription }
f60cee492a6ded42a66ee1aa642aa80f
44.187739
407
0.54019
false
false
false
false
cyanzhong/TodayMind
refs/heads/master
TodayMind/Main/View/SwitchCell.swift
gpl-3.0
2
// // SwitchCell.swift // TodayMind // // Created by cyan on 2017/2/21. // Copyright © 2017 cyan. All rights reserved. // import UIKit import TMKit class SwitchCell: BaseCell { let switcher = UISwitch() init(title: String, identifier: String, on: Bool) { super.init(style: .default, reuseIdentifier: identifier) textLabel?.text = title switcher.isOn = on accessoryView = switcher selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
44e488d36fdec6b252ee8b01f4a9296e
19.444444
60
0.67029
false
false
false
false
gservera/ScheduleKit
refs/heads/master
ScheduleKit/BaseDefinitions.swift
mit
1
/* * BaseDefinitions.swift * ScheduleKit * * Created: Guillem Servera on 24/12/2014. * Copyright: © 2014-2019 Guillem Servera (https://github.com/gservera) * * 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 Cocoa /// The shared calendar object used by the ScheduleKit framework. var sharedCalendar = Calendar.current /// A `Double` value that represents relative time points between the lower and /// upper date bounds in a concrete `SCKView` subclass. Valid values are the ones /// between 0.0 and 1.0, which represent the start date and the end date, /// respectively. Any other values are not valid and should be represented using /// `SCKRelativeTimeLocationInvalid`. internal typealias SCKRelativeTimeLocation = Double /// A `Double` value that represents the relative length (in percentage) for an /// event in a concrete `SCKView` subclass. Valid values are the ones /// between 0.0 and 1.0, which represent zero-length and full length values, /// respectively. Behaviour when using any other values in undefined. internal typealias SCKRelativeTimeLength = Double /// A fallback value generated by ScheduleKit the date of an event object used /// in a `SCKView` subclass does not fit in the view's date interval. internal let SCKRelativeTimeLocationInvalid = SCKRelativeTimeLocation(-Int.max) /// A fallback value generated by ScheduleKit the duration of an event object used /// in a `SCKView` subclass is invalid (negative or too wide). internal let SCKRelativeTimeLengthInvalid = SCKRelativeTimeLocation.leastNormalMagnitude /// Possible color styles for drawing event view backgrounds. @objc public enum SCKEventColorMode: Int { /// Colors events according to their event kind. case byEventKind /// Colors events according to their user's event color. case byEventOwner } extension Calendar { func dateInterval(_ interval: DateInterval, offsetBy value: Int, _ unit: Calendar.Component) -> DateInterval { let start = date(byAdding: unit, value: value, to: interval.start) let end = date(byAdding: unit, value: value, to: interval.end) return DateInterval(start: start!, end: end!) } } extension NSTextField { static func makeLabel(fontSize: CGFloat, color: NSColor) -> NSTextField { let label = NSTextField(frame: .zero) label.translatesAutoresizingMaskIntoConstraints = false label.isBordered = false label.isEditable = false label.isBezeled = false label.drawsBackground = false label.font = .systemFont(ofSize: fontSize) label.textColor = color return label } } extension CGRect { static func fill(_ xPos: CGFloat, _ yPos: CGFloat, _ wDim: CGFloat, _ hDim: CGFloat) { CGRect(x: xPos, y: yPos, width: wDim, height: hDim).fill() } }
b0fe5be72971465a696561c9ba321f40
40.591398
114
0.732678
false
false
false
false
seankim2/TodayWeather
refs/heads/master
ios/watch Extension/WatchTWeatherDraw.swift
mit
1
// // WatchTWeatherDraw.swift // watch Extension // // Created by KwangHo Kim on 2017. 11. 6.. // import WatchKit import WatchConnectivity import Foundation //let watchTWUtil = WatchTWeatherUtil(); class WatchTWeatherDraw : WKInterfaceController{ // @IBOutlet var updateDateLabel: WKInterfaceLabel! // @IBOutlet var currentPosImage: WKInterfaceImage! // @IBOutlet var addressLabel: WKInterfaceLabel! // @IBOutlet var curWeatherImage: WKInterfaceImage! // // @IBOutlet var curTempLabel: WKInterfaceLabel! // @IBOutlet var minMaxLabel: WKInterfaceLabel! // // @IBOutlet var precLabel: WKInterfaceLabel! // @IBOutlet var airAQILabel: WKInterfaceLabel! var curJsonDict : Dictionary<String, Any>? = nil; // Singleton static let sharedInstance : WatchTWeatherDraw = { let instance = WatchTWeatherDraw() //setup code return instance }() #if false struct StaticInstance { static var instance: WatchTWeatherDraw? } class func sharedInstance() -> WatchTWeatherDraw { if !(StaticInstance.instance != nil) { StaticInstance.instance = WatchTWeatherDraw() } return StaticInstance.instance! } #endif // let watchTWUtil = WatchTWeatherUtil.sharedInstance(); // let watchTWReq = WatchTWeatherRequest.sharedInstance(); // let watchTWSM = WatchTWeatherShowMore.sharedInstance(); #if false func processWeatherResultsWithShowMore( jsonDict : Dictionary<String, AnyObject>?) { //var currentDict : Dictionary<String, Any>; //var currentArpltnDict : Dictionary<String, Any>; var todayDict : Dictionary<String, Any>; // Date var strDateTime : String!; //var strTime : String? = nil; // Image //var strCurIcon : String? = nil; var strCurImgName : String? = nil; // Temperature var currentTemp : Float = 0; var todayMinTemp : Int = 0; var todayMaxTemp : Int = 0; // Dust var strAirState : String = ""; var attrStrAirState : NSAttributedString = NSAttributedString(); //NSMutableAttributedString *nsmasAirState = nil; // Address var strAddress : String? = nil; // Pop var numberTodPop : NSNumber; var todayPop : Int = 0; // current temperature var numberT1h : NSNumber; var numberTaMin : NSNumber; var numberTaMax : NSNumber; if(jsonDict == nil) { print("jsonDict is nil!!!"); return; } //print("processWeatherResultsWithShowMore : \(String(describing: jsonDict))"); setCurJsonDict( dict : jsonDict! ) ; // Address if let strRegionName : String = jsonDict?["regionName"] as? String { print("strRegionName is \(strRegionName).") strAddress = strRegionName; } else { print("That strRegionName is not in the jsonDict dictionary.") } if let strCityName : String = jsonDict?["cityName"] as? String { print("strCityName is \(strCityName).") strAddress = strCityName; } else { print("That strCityName is not in the jsonDict dictionary.") } if let strTownName : String = jsonDict?["townName"] as? String { print("strTownName is \(strTownName).") strAddress = strTownName; } else { print("That strTownName is not in the jsonDict dictionary.") } // if address is current position... add this emoji //목격자 //유니코드: U+1F441 U+200D U+1F5E8, UTF-8: F0 9F 91 81 E2 80 8D F0 9F 97 A8 print("strAddress \(String(describing: strAddress)))") strAddress = NSString(format: "👁‍🗨%@˚", strAddress!) as String let tempUnit : TEMP_UNIT? = watchTWUtil.getTemperatureUnit(); //#if KKH // Current if let currentDict : Dictionary<String, Any> = jsonDict?["current"] as? Dictionary<String, Any>{ //print("currentDict is \(currentDict).") if let strCurIcon : String = currentDict["skyIcon"] as? String { //strCurImgName = "weatherIcon2-color/\(strCurIcon).png"; strCurImgName = strCurIcon; } else { print("That strCurIcon is not in the jsonDict dictionary.") } if let strTime : String = currentDict["time"] as? String { let index = strTime.index(strTime.startIndex, offsetBy: 2) //let strHour = strTime.substring(to:index); let strHour = strTime[..<index]; //let strMinute = strTime.substring(from:index); let strMinute = strTime[index...]; strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHour + ":" + strMinute; print("strTime => \(strTime)") print("strHour => \(strHour)") print("strMinute => \(strMinute)") } else { print("That strTime is not in the jsonDict dictionary.") strDateTime = ""; } print("strDateTime => \(strDateTime)") if let currentArpltnDict : Dictionary<String, Any> = currentDict["arpltn"] as? Dictionary<String, Any> { strAirState = watchTWSM.getAirState(currentArpltnDict); // Test //nssAirState = [NSString stringWithFormat:@"통합대기 78 나쁨"]; attrStrAirState = watchTWSM.getChangedColorAirState(strAirState:strAirState); print("[processWeatherResultsWithShowMore] attrStrAirState : \(String(describing: attrStrAirState))"); print("[processWeatherResultsWithShowMore] strAirState : \(String(describing: strAirState))"); } else { print("That currentArpltnDict is not in the jsonDict dictionary.") } if (currentDict["t1h"] != nil) { numberT1h = currentDict["t1h"] as! NSNumber; currentTemp = Float(numberT1h.doubleValue); if(tempUnit == TEMP_UNIT.FAHRENHEIT) { currentTemp = Float(watchTWUtil.convertFromCelsToFahr(cels: currentTemp)); } } } else { print("That currentDict is not in the jsonDict dictionary.") } //currentHum = [[currentDict valueForKey:@"reh"] intValue]; todayDict = watchTWUtil.getTodayDictionary(jsonDict: jsonDict!); // Today if (todayDict["taMin"] != nil) { numberTaMin = todayDict["taMin"] as! NSNumber; todayMinTemp = Int(numberTaMin.intValue); } else { print("That idTaMin is not in the todayDict dictionary.") } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { todayMinTemp = Int( watchTWUtil.convertFromCelsToFahr(cels: Float(todayMinTemp) ) ); } if (todayDict["taMax"] != nil) { numberTaMax = todayDict["taMax"] as! NSNumber; todayMaxTemp = Int(numberTaMax.intValue); } else { print("That numberTaMax is not in the todayDict dictionary.") } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { todayMaxTemp = Int(watchTWUtil.convertFromCelsToFahr(cels: Float(todayMaxTemp) )) ; } if (todayDict["pop"] != nil) { numberTodPop = todayDict["pop"] as! NSNumber; todayPop = Int(numberTodPop.intValue); } else { print("That pop is not in the todayDict dictionary.") } print("todayMinTemp: \(todayMinTemp), todayMaxTemp:\(todayMaxTemp)"); print("todayPop: \(todayPop)"); DispatchQueue.global(qos: .background).async { // Background Thread DispatchQueue.main.async { // Run UI Updates if(strDateTime != nil) { self.updateDateLabel.setText("\(strDateTime!)"); } print("=======> date : \(strDateTime!)"); if( (strAddress == nil) || ( strAddress == "(null)" )) { self.addressLabel.setText(""); } else { self.addressLabel.setText("\(strAddress!)"); } print("=======> strCurImgName : \(strCurImgName!)"); if(strCurImgName != nil) { self.curWeatherImage.setImage ( UIImage(named:strCurImgName!) ); } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { self.curTempLabel.setText( NSString(format: "%d˚", currentTemp) as String ); } else { self.curTempLabel.setText( NSString(format: "%.01f˚", currentTemp) as String); } print("[processWeatherResultsWithShowMore] attrStrAirState2 : \(String(describing: attrStrAirState))"); self.airAQILabel.setAttributedText( attrStrAirState ); self.minMaxLabel.setText(NSString(format: "%d˚/ %d˚", todayMinTemp, todayMaxTemp) as String ); self.precLabel.setText(NSString(format: "%d%%", todayPop) as String ); //locationView.hidden = false; } } //#endif // Draw ShowMore //[todayWSM processDailyData:jsonDict type:TYPE_REQUEST_WEATHER_KR]; } func processWeatherResultsAboutGlobal( jsonDict : Dictionary<String, AnyObject>?) { let watchTWSM = WatchTWeatherShowMore(); var currentDict : Dictionary<String, Any>; //var currentArpltnDict : Dictionary<String, Any>; var todayDict : Dictionary<String, Any>? = nil; // Date var strDateTime : String!; //var strTime : String? = nil; // Image //var strCurIcon : String? = nil; var strCurImgName : String? = nil; // Temperature var tempUnit : TEMP_UNIT? = TEMP_UNIT.CELSIUS; var currentTemp : Float = 0; var todayMinTemp : Int = 0; var todayMaxTemp : Int = 0; // Dust var strAirState : String = ""; var attrStrAirState : NSAttributedString = NSAttributedString(); //NSMutableAttributedString *nsmasAirState = nil; // Address var strAddress : String? = nil; // Pop var numberTodPop : NSNumber; var todayPop : Int = 0; // Humid var numberTodHumid : NSNumber; var todayHumid = 0; if(jsonDict == nil) { print("jsonDict is nil!!!"); return; } //print("processWeatherResultsWithShowMore : \(String(describing: jsonDict))"); setCurJsonDict( dict : jsonDict! ) ; // Address //NSLog(@"mCurrentCityIdx : %d", mCurrentCityIdx); //NSMutableDictionary* nsdCurCity = [mCityDictList objectAtIndex:mCurrentCityIdx]; //NSLog(@"[processWeatherResultsAboutGlobal] nsdCurCity : %@", nsdCurCity); // Address //nssAddress = [nsdCurCity objectForKey:@"name"]; //nssCountry = [nsdCurCity objectForKey:@"country"]; //if(nssCountry == nil) //{ // nssCountry = @"KR"; //} //NSLog(@"[Global]nssAddress : %@, nssCountry : %@", nssAddress, nssCountry); // if address is current position... add this emoji //목격자 //유니코드: U+1F441 U+200D U+1F5E8, UTF-8: F0 9F 91 81 E2 80 8D F0 9F 97 A8 //print("strAddress \(String(describing: strAddress)))") //strAddress = NSString(format: "👁‍🗨%@˚", strAddress!) as String strAddress = NSString(format: "뉴욕") as String; // Current if let thisTimeArr : NSArray = jsonDict?["thisTime"] as? NSArray { if(thisTimeArr.count == 2) { currentDict = thisTimeArr[1] as! Dictionary<String, Any>; // Use second index; That is current weahter. } else { currentDict = thisTimeArr[0] as! Dictionary<String, Any>; // process about thisTime } if let strCurIcon : String = currentDict["skyIcon"] as? String { //strCurImgName = "weatherIcon2-color/\(strCurIcon).png"; strCurImgName = strCurIcon; } else { print("That strCurIcon is not in the jsonDict dictionary.") } tempUnit = watchTWUtil.getTemperatureUnit(); if let strTime : String = currentDict["date"] as? String { let index = strTime.index(strTime.startIndex, offsetBy: 11) let strHourMin = strTime[index...]; strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHourMin; print("strTime => \(strHourMin)") todayDict = watchTWUtil.getTodayDictionaryInGlobal(jsonDict: jsonDict!, strTime:strTime); if(todayDict != nil) { if(tempUnit == TEMP_UNIT.FAHRENHEIT) { let idTaMin = todayDict!["tempMin_f"] as! NSNumber; todayMinTemp = Int(truncating: idTaMin); let idTaMax = todayDict!["tempMax_f"] as! NSNumber; todayMaxTemp = Int(truncating: idTaMax); } else { let idTaMin = todayDict!["tempMin_c"] as! NSNumber; todayMinTemp = Int(truncating: idTaMin); let idTaMax = todayDict!["tempMax_c"] as! NSNumber; todayMaxTemp = Int(truncating: idTaMax); } // PROBABILITY_OF_PRECIPITATION if (todayDict!["precProb"] != nil) { numberTodPop = todayDict!["precProb"] as! NSNumber; todayPop = Int(numberTodPop.intValue); } else { print("That precProb is not in the todayDict dictionary.") } // HUMID if (todayDict!["humid"] != nil) { numberTodHumid = todayDict!["humid"] as! NSNumber; todayHumid = Int(numberTodHumid.intValue); } else { print("That humid is not in the todayDict dictionary.") } strAirState = NSLocalizedString("LOC_HUMIDITY", comment:"습도") + " \(todayHumid)% "; } } else { print("That strTime is not in the jsonDict dictionary.") let strHourMin = ""; strDateTime = NSLocalizedString("LOC_UPDATE", comment:"업데이트") + " " + strHourMin; } print("strDateTime => \(strDateTime)") if(tempUnit == TEMP_UNIT.FAHRENHEIT) { let idT1h = currentDict["temp_f"] as! NSNumber; currentTemp = Float(Int(truncating: idT1h)); } else { let idT1h = currentDict["temp_c"] as! NSNumber; currentTemp = Float(truncating: idT1h); } } print("todayMinTemp: \(todayMinTemp), todayMaxTemp:\(todayMaxTemp)"); print("todayPop: \(todayPop)"); #if KKH if let currentDict : Dictionary<String, Any> = jsonDict?["current"] as? Dictionary<String, Any>{ //print("currentDict is \(currentDict).") if let currentArpltnDict : Dictionary<String, Any> = currentDict["arpltn"] as? Dictionary<String, Any> { strAirState = watchTWSM.getAirState(currentArpltnDict); // Test //nssAirState = [NSString stringWithFormat:@"통합대기 78 나쁨"]; attrStrAirState = watchTWSM.getChangedColorAirState(strAirState:strAirState); print("[processWeatherResultsWithShowMore] attrStrAirState : \(String(describing: attrStrAirState))"); print("[processWeatherResultsWithShowMore] strAirState : \(String(describing: strAirState))"); } else { print("That currentArpltnDict is not in the jsonDict dictionary.") } } else { print("That currentDict is not in the jsonDict dictionary.") } #endif DispatchQueue.global(qos: .background).async { // Background Thread DispatchQueue.main.async { // Run UI Updates if(strDateTime != nil) { self.updateDateLabel.setText("\(strDateTime!)"); } print("=======> date : \(strDateTime!)"); if( (strAddress == nil) || ( strAddress == "(null)" )) { self.addressLabel.setText(""); } else { self.addressLabel.setText("\(strAddress!)"); } print("=======> strCurImgName : \(strCurImgName!)"); strCurImgName = "MoonBigCloudRainLightning"; if(strCurImgName != nil) { self.curWeatherImage.setImage ( UIImage(named:"Moon"/*strCurImgName!*/) ); print("111=======> strCurImgName : \(strCurImgName!)"); } if(tempUnit == TEMP_UNIT.FAHRENHEIT) { self.curTempLabel.setText( NSString(format: "%d˚", currentTemp) as String ); } else { self.curTempLabel.setText( NSString(format: "%.01f˚", currentTemp) as String); } #if KKH print("[processWeatherResultsWithShowMore] attrStrAirState2 : \(String(describing: attrStrAirState))"); self.airAQILabel.setAttributedText( attrStrAirState ); #endif self.minMaxLabel.setText(NSString(format: "%d˚/ %d˚", todayMinTemp, todayMaxTemp) as String ); self.precLabel.setText(NSString(format: "%d%%", todayPop) as String ); self.airAQILabel.setText(strAirState); //locationView.hidden = false; } } //#endif // Draw ShowMore //[todayWSM processDailyData:jsonDict type:TYPE_REQUEST_WEATHER_KR]; } #endif func setCurJsonDict( dict : Dictionary<String, Any> ) { if(curJsonDict == nil) { curJsonDict = [String : String] () } else { curJsonDict = dict; } } }
ac6ca5f3086db460aa7f84f314dee948
30.706796
122
0.622512
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/PageIDToURLFetcher.swift
mit
1
import Foundation public final class PageIDToURLFetcher: Fetcher { private let maxNumPageIDs = 50 /// Fetches equivalent page URLs for every pageID passed in. Automatically makes additional calls if number of pageIDs is greater than API maximum (50). public func fetchPageURLs(_ siteURL: URL, pageIDs: [Int], failure: @escaping WMFErrorHandler, success: @escaping ([URL]) -> Void) { guard !pageIDs.isEmpty else { failure(RequestError.invalidParameters) return } let pageIDChunks = pageIDs.chunked(into: maxNumPageIDs) var finalURLs: [URL] = [] var errors: [Error] = [] let group = DispatchGroup() for pageIDChunk in pageIDChunks { group.enter() fetchMaximumPageURLs(siteURL, pageIDs: pageIDChunk) { error in DispatchQueue.main.async { errors.append(error) group.leave() } } success: { urls in DispatchQueue.main.async { finalURLs.append(contentsOf: urls) group.leave() } } } group.notify(queue: .main) { if let error = errors.first { failure(error) } else if finalURLs.isEmpty { failure(RequestError.unexpectedResponse) } else { success(finalURLs) } } } /// Fetches equivalent page URLs for every pageID passed in. Maximum of 50 page IDs allowed. Use fetchPageURLs(siteURL:pageID:failure:success) method if requesting > 50 pageIDs. private func fetchMaximumPageURLs(_ siteURL: URL, pageIDs: [Int], failure: @escaping WMFErrorHandler, success: @escaping ([URL]) -> Void) { guard pageIDs.count <= maxNumPageIDs else { failure(RequestError.invalidParameters) return } var params: [String: AnyObject] = [ "action": "query" as AnyObject, "prop": "info" as AnyObject, "inprop": "url" as AnyObject, "format": "json" as AnyObject ] let stringPageIDs = pageIDs.map { String($0) } params["pageids"] = stringPageIDs.joined(separator: "|") as AnyObject performMediaWikiAPIGET(for: siteURL, with: params, cancellationKey: nil) { (result, response, error) in if let error = error { failure(error) return } guard let result = result else { failure(RequestError.unexpectedResponse) return } guard let query = result["query"] as? [String: Any], let pages = query["pages"] as? [String: AnyObject] else { failure(RequestError.unexpectedResponse) return } var finalURLs: [URL] = [] for (_, value) in pages { guard let fullURLString = value["fullurl"] as? String, let url = URL(string: fullURLString) else { continue } finalURLs.append(url) } success(finalURLs) } } }
dcf3dd65ee194cb777bb8260d9c77e04
33
181
0.539216
false
false
false
false
alblue/swift
refs/heads/master
test/SILOptimizer/definite-init-wrongscope.swift
apache-2.0
3
// RUN: %target-swift-frontend -primary-file %s -Onone -emit-sil -Xllvm \ // RUN: -sil-print-after=raw-sil-inst-lowering -Xllvm \ // RUN: -sil-print-only-functions=$s3del1MC4fromAcA12WithDelegate_p_tKcfc \ // RUN: -Xllvm -sil-print-debuginfo -o /dev/null 2>&1 | %FileCheck %s public protocol DelegateA {} public protocol DelegateB {} public protocol WithDelegate { var delegate: DelegateA? { get } func f() throws -> Int } public enum Err: Swift.Error { case s(Int) } public class C {} public class M { let field: C var value : Int public init(from d: WithDelegate) throws { guard let delegate = d.delegate as? DelegateB else { throw Err.s(0) } self.field = C() let i: Int = try d.f() value = i } } // Make sure the expanded sequence gets the right scope. // CHECK: [[I:%.*]] = integer_literal $Builtin.Int2, 1, loc {{.*}}:20:12, scope 2 // CHECK: [[V:%.*]] = load [trivial] %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: [[OR:%.*]] = builtin "or_Int2"([[V]] : $Builtin.Int2, [[I]] : $Builtin.Int2) : $Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: store [[OR]] to [trivial] %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: store %{{.*}} to [init] %{{.*}} : $*C, loc {{.*}}:23:20, scope 2 // Make sure the dealloc_stack gets the same scope of the instructions surrounding it. // CHECK: destroy_addr %0 : $*WithDelegate, loc {{.*}}:26:5, scope 2 // CHECK: dealloc_stack %2 : $*Builtin.Int2, loc {{.*}}:20:12, scope 2 // CHECK: throw %{{.*}} : $Error, loc {{.*}}:20:12, scope 2
f27edf3fd981cd7f00ae51c75d37f704
37.829268
131
0.593593
false
false
false
false
delbert06/DYZB
refs/heads/master
DYZB/DYZB/HomeViewController.swift
mit
1
// // HomeViewController.swift // DYZB // // Created by 胡迪 on 2016/10/17. // Copyright © 2016年 D.Huhu. All rights reserved. // import UIKit private let ktitleViewH : CGFloat = 40 class HomeViewController: UIViewController { //MARK: -懒加载属性 lazy var pageTitleView:PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStautusBarH + kNavigationBarH, width: kScreenW, height: ktitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() lazy var pageContentView:PageContentView = { let contentH = kScreenH - kStautusBarH - kNavigationBarH - ktitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStautusBarH + kNavigationBarH + ktitleViewH, width: kScreenW, height: contentH) var childVCs = [UIViewController]() childVCs.append(RecommendViewController()) childVCs.append(GameViewController()) childVCs.append(PlayViewController()) let contentView = PageContentView(frame: contentFrame, childVCs: childVCs, parentVC: self) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: - 设置UI界面 extension HomeViewController{ func setupUI(){ //不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false setNavigationBar() view.addSubview(pageTitleView) view.addSubview(pageContentView) } private func setNavigationBar(){ // 1. 设置左边的item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") // 2. 创建UICollectionView let size = CGSize(width: 40, height: 40) let his = UIBarButtonItem(imageName: "image_my_history", highImage: "Image_my_history_click", size: size) let scan = UIBarButtonItem(imageName: "Image_scan", highImage: "Image_scan_click", size: size) let search = UIBarButtonItem(imageName: "btn_search", highImage: "btn_search_clicked", size: size) navigationItem.rightBarButtonItems = [his,scan,search] } } //MARK: - 遵守PageTitleView协议 extension HomeViewController:PageTitleViewDelegate{ func pageTitle(titleView: PageTitleView, selectedIndex Index: Int) { pageContentView.setCurrentIndex(currnetIndex: Index) } } extension HomeViewController : PageCollectViewDelegate{ func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
e2a420feb515d2ee7b63d3df13a72386
30.829787
123
0.662099
false
false
false
false
hawkfalcon/Clients
refs/heads/master
Clients/ViewControllers/ClientInfoViewController.swift
mit
1
import UIKit import Contacts import ContactsUI import CoreData class ClientInfoViewController: UITableViewController { var sections = [String]() var dataContext: NSManagedObjectContext! var client: Client! // MARK: - Setup override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self var title = "New Contact" sections = ["Contact", "Categories", "Driving", "Other"] if !Settings.enabledMileage { sections.remove(at: 2) } if let client = client { if let first = client.firstName, let last = client.lastName { title = "\(first) \(last)" } for category in client.categories! { let category = category as! Category sections.insert(category.name!, at: 2) } } else { client = Client(context: dataContext) client.timestamp = NSDate() client.notes = "" client.firstName = "First" client.lastName = "Last" } navigationItem.title = title dataContext.saveChanges() } override func viewWillAppear(_ animated: Bool) { tableView.reloadData() client!.complete = client.owed() == 0.0 dataContext.saveChanges() super.viewWillAppear(animated) } // MARK: - Populate data override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = indexPath.section var cell: UITableViewCell if sections[section] == "Other" { cell = createNotesCell(indexPath: indexPath) } else if isCategory(section) { cell = createPaymentCell(section: section, indexPath: indexPath) } else { cell = createInfoCell(section: sections[section], indexPath: indexPath) } return cell } func createNotesCell(indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NotesCell", for: indexPath) as! TextInputCell cell.textLabel?.text = "Notes" if let notes = client.notes { cell.textField.text = notes } cell.detailTextLabel?.lineBreakMode = .byWordWrapping; cell.detailTextLabel?.numberOfLines = 0; cell.textField.delegate = self cell.textField.addTarget(self, action: #selector(fieldDidChange), for: .editingChanged) cell.textField.placeholder = "Notes..." cell.textField.isEnabled = true cell.textField.keyboardType = .default cell.textField.frame.size.height = cell.frame.size.height * (9 / 10) return cell } func createPaymentCell(section: Int, indexPath: IndexPath) -> UITableViewCell { let last = tableView.numberOfRows(inSection: indexPath.section) - 1 if indexPath.row == last { let cell = tableView.dequeueReusableCell(withIdentifier: "NewPaymentCell", for: indexPath) as! NewPaymentCell cell.configure(type: "Payment") return cell } else { let category = client.category(section: section)! let identifier = indexPath.row == 0 ? "PaymentTotalCell" : "PaymentCell" let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! PaymentDataCell if indexPath.row == 0 { configure(cell, for: category) } else { let payment = category.payments!.object(at: indexPath.row - 1) as! Payment cell.paymentField.text = payment.name cell.valueField.text = "\(payment.value.currency)" cell.valueField.isEnabled = false } cell.addTargets(viewController: self) return cell } } func configure(_ cell: PaymentDataCell, for category: Category) { let leftLabel = UILabel() leftLabel.text = "Total: " leftLabel.textAlignment = .right leftLabel.font = UIFont.boldSystemFont(ofSize: 16) leftLabel.sizeToFit() cell.valueField.leftView = leftLabel cell.valueField.leftViewMode = .unlessEditing cell.paymentField.text = category.name cell.paymentField.isEnabled = false cell.paymentField.font = UIFont.boldSystemFont(ofSize: 16) cell.valueField.text = "\(category.total.currency)" cell.valueField.sizeToFit() cell.backgroundColor = UIColor.lightText cell.selectionStyle = .none cell.accessoryType = .none } func createInfoCell(section: String, indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell", for: indexPath) var title = "" var value = "" switch section { case "Contact": title = navigationItem.title! if (title == "New Contact") { title = "Choose a Contact" } value = "Go to Contact" case "Driving": title = "Miles Driven" //TODO recalcuate on segue from Mileage var mileTotal: Double = 0.0 for mile in client.mileage! { let mile = mile as! Mileage mileTotal += mile.miles } value = "\(mileTotal)" case "Categories": if client.categories!.count == 0 { title = "Add a Category +" } default: print("?") } if section == "Contact" || section == "Driving" { cell.selectionStyle = .default cell.accessoryType = .disclosureIndicator } else { cell.accessoryType = .none cell.selectionStyle = .none } cell.textLabel?.text = title cell.detailTextLabel?.text = value return cell } // MARK: - Tapped on cell override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath)! as UITableViewCell if let text = cell.detailTextLabel?.text, text == "Go to Contact" { if let contact = client.contact { loadContact(identifier: contact) } else { showContactsPicker() } } else if let text = cell.textLabel?.text, text == "Miles Driven" { performSegue(withIdentifier: "toMiles", sender: nil) } else if let text = cell.textLabel?.text, text == "Add a Category +" { performSegue(withIdentifier: "addCategory", sender: nil) } else if cell is NewPaymentCell { let category = client.category(section: indexPath.section) let payment = Payment(context: dataContext) payment.name = Settings.defaultPaymentNames[0] payment.type = Settings.defaultPaymentType payment.value = 0.0 payment.date = NSDate() category?.addToPayments(payment) dataContext.saveChanges() tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) self.performSegue(withIdentifier: "toPayment", sender: self) } else { if let textCell = cell as? TextInputCell, textCell.textField != nil { textCell.textField.becomeFirstResponder() } } } // MARK: - Setup layout override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isCategory(section) { let category = client.category(section: section)! return category.payments!.count + 2 } return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let category = sections[section] if isCategory(section) { return nil } return category } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let section = sections[indexPath.section] switch section { case "Other": return 150.0 case "Categories": if client.categories!.count == 0 { return 55.0 } return 0 case "Driving": return 55.0 case "Contact": return 55.0 default: if indexPath.row == 0 { return 35.0 } return 55.0 } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if isCategory(indexPath.section) && indexPath.row == 0 { return nil } return indexPath } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let category = sections[section] if isCategory(section) || category == "Categories" { return 0.0001 } return 18.0; } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let category = sections[section] if isCategory(section) { return 0.0001 } else if category == "Contact" || category == "Driving" || (category == "Other" && !Settings.enabledMileage) { return 36.0 } return 18.0; } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let last = tableView.numberOfRows(inSection: indexPath.section) - 1 if isCategory(indexPath.section) && indexPath.row != last { return true } return false } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { tableView.endEditing(true) } // MARK: - Allow deletion override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { tableView.beginUpdates() if indexPath.row == 0 { client.removeFromCategories(at: indexPath.section - 2) sections.remove(at: 2) tableView.deleteSections([indexPath.section], with: .automatic) if client.categories!.count == 0 { let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 1)) cell!.textLabel!.text = "Add a Category +" } } else { let category = client.category(section: indexPath.section)! category.removeFromPayments(at: indexPath.row - 1) tableView.deleteRows(at: [indexPath], with: .automatic) } dataContext.saveChanges() tableView.endUpdates() } } // MARK: - Return from new category @IBAction func unwindAndAddCategory(_ segue: UIStoryboardSegue) { let source = segue.source as! NewCategoryViewController let category = Category(context: dataContext) category.name = source.name category.total = source.total client.addToCategories(category) dataContext.saveChanges() sections.insert(category.name!, at: 2) tableView.reloadData() } @IBAction func unwindToClient(_ segue: UIStoryboardSegue) { //Cancelled } // Prepare to edit client or go to mileage override func prepare(for segue: UIStoryboardSegue, sender: Any!) { if let id = segue.identifier { if id == "toMiles", let destination = segue.destination as? MileageTableViewController { destination.mileage = client.mileage! destination.client = client destination.dataContext = dataContext } else if id == "toPayment", let destination = segue.destination as? PaymentInfoViewController { if let index = tableView.indexPathForSelectedRow { let category = client.category(section: index.section)! let payment = category.payments!.object(at: index.row - 1) as! Payment destination.payment = payment } } } } func isCategory(_ section: Int) -> Bool { return section > 1 && section < client.categories!.count + 2 } } extension NSManagedObjectContext { func saveChanges() { if self.hasChanges { do { try self.save() } catch { print("An error occurred while saving: \(error)") } } } } extension ClientInfoViewController: UITextFieldDelegate { // Allow editing in place func fieldDidChange(_ textField: UITextField) { if let name = textField.placeholder, let cell = textField.superview?.superview as? UITableViewCell, let indexPath = tableView.indexPath(for: cell), let text = textField.text { if name == "Notes..." { client.notes = text } else if let category = client.category(section: indexPath.section) { if indexPath.row > 0 { let payment = category.payments!.object(at: indexPath.row - 1) as! Payment if name == "Name" { payment.name = text } else if let value = text.rawDouble { payment.value = value } } else if let value = text.rawDouble { category.total = value } } dataContext.saveChanges() } } // Setup reponse func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } func textFieldDidEndEditing(_ textField: UITextField) { if let money = textField.text?.rawDouble { textField.text = money.currency } } /*func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { return range.length < 1 || range.location + range.length > 1 }*/ } extension ClientInfoViewController: CNContactPickerDelegate { func loadContact(identifier: String) { do { let contact = try CNContactStore().unifiedContact(withIdentifier: identifier, keysToFetch: [CNContactViewController.descriptorForRequiredKeys()]) let viewController = CNContactViewController(for: contact) viewController.contactStore = CNContactStore() viewController.delegate = self self.navigationController?.pushViewController(viewController, animated: true) } catch { print("Can't load contact") } } func showContactsPicker() { let contactPicker = CNContactPickerViewController() contactPicker.delegate = self; // TODO: fix predicate // let predicate = NSPredicate(format: "phoneNumbers.@count > 0") // contactPicker.predicateForEnablingContact = predicate self.present(contactPicker, animated: true, completion: nil) } } extension ClientInfoViewController: CNContactViewControllerDelegate { func contactPicker(_ picker: CNContactPickerViewController, didSelect contactSelected: CNContact) { client.contact = contactSelected.identifier client.firstName = contactSelected.givenName client.lastName = contactSelected.familyName dataContext.saveChanges() navigationItem.title = "\(contactSelected.givenName) \(contactSelected.familyName)" } } extension Client { func category(section: Int) -> Category? { return self.categories!.object(at: section - 2) as? Category } } extension Double { var currency: String { let formatter = NumberFormatter() formatter.numberStyle = .currency return formatter.string(from: NSNumber(value: self))! } } extension String { var rawDouble: Double? { var raw = self.replacingOccurrences(of: "$", with: "") raw = raw.replacingOccurrences(of: ",", with: "") return Double(raw) } }
86cfc2e00ba980b9583f5e3ac4b64f60
34.033755
157
0.594424
false
false
false
false
mckaskle/FlintKit
refs/heads/master
FlintKit/UIKit/NetworkActivityIndicatorManager.swift
mit
1
// // MIT License // // NetworkActivityIndicatorManager.swift // // Copyright (c) 2016 Devin McKaskle // // 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 @available(iOS 10.0, *) @available(iOSApplicationExtension, unavailable) public final class NetworkActivityIndicatorManager { // MARK: - Enum private enum State { case notActive, delayingStart, active, delayingEnd } // MARK: - Object Lifecycle init(application: UIApplication) { self.application = application } // MARK: - Public Properties static public let shared = NetworkActivityIndicatorManager(application: .shared) public private(set) var activityCount = 0 { didSet { switch state { case .notActive: if activityCount > 0 { state = .delayingStart } case .delayingStart: // No-op, let the timer finish. break case .active: if activityCount <= 0 { state = .delayingEnd } case .delayingEnd: if activityCount > 0 { state = .active } } } } // MARK: - Public Methods public func incrementActivityCount() { let f = { self.activityCount += 1 } if Thread.isMainThread { f() } else { DispatchQueue.main.async(execute: f) } } public func decrementActivityCount() { let f = { self.activityCount = max(0, self.activityCount - 1) } if Thread.isMainThread { f() } else { DispatchQueue.main.async(execute: f) } } // MARK: - Private Properties private let application: UIApplication private var startTimer: Timer? private var endTimer: Timer? private var state: State = .notActive { didSet { switch state { case .notActive: startTimer?.invalidate() endTimer?.invalidate() application.isNetworkActivityIndicatorVisible = false case .delayingStart: // Apple's HIG describes the following: // > Display the network activity indicator to provide feedback when your app accesses // > the network for more than a couple of seconds. If the operation finishes sooner // > than that, you don’t have to show the network activity indicator, because the // > indicator is likely to disappear before users notice its presence. startTimer = .scheduledTimer(withTimeInterval: 1, repeats: false) { [weak self] _ in guard let s = self else { return } s.state = s.activityCount > 0 ? .active : .notActive } case .active: endTimer?.invalidate() application.isNetworkActivityIndicatorVisible = true case .delayingEnd: endTimer?.invalidate() // Delay hiding the indicator so that if multiple requests are happening one after another, // there is one continuous showing of the network indicator. endTimer = .scheduledTimer(withTimeInterval: 0.17, repeats: false) { [weak self] _ in self?.state = .notActive } } } } }
f703a44d50359d8e90ff3d174381f2da
28.70922
99
0.650036
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Home/RecentlySaved/RecentlySavedCell.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import Storage /// A cell used in FxHomeScreen's Recently Saved section. It holds bookmarks and reading list items. class RecentlySavedCell: UICollectionViewCell, ReusableCell { private struct UX { static let bookmarkTitleFontSize: CGFloat = 12 static let containerSpacing: CGFloat = 16 static let heroImageSize: CGSize = CGSize(width: 126, height: 82) static let fallbackFaviconSize = CGSize(width: 36, height: 36) static let generalSpacing: CGFloat = 8 } // MARK: - UI Elements private var rootContainer: UIView = .build { view in view.backgroundColor = .clear view.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius } // Contains the hero image and fallback favicons private var imageContainer: UIView = .build { view in view.backgroundColor = .clear } let heroImageView: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.masksToBounds = true imageView.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius } // Used as a fallback if hero image isn't set private let fallbackFaviconImage: UIImageView = .build { imageView in imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true imageView.backgroundColor = .clear imageView.layer.cornerRadius = HomepageViewModel.UX.generalIconCornerRadius imageView.layer.masksToBounds = true } private var fallbackFaviconBackground: UIView = .build { view in view.layer.cornerRadius = HomepageViewModel.UX.generalCornerRadius view.layer.borderWidth = HomepageViewModel.UX.generalBorderWidth } let itemTitle: UILabel = .build { label in label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, size: UX.bookmarkTitleFontSize) label.adjustsFontForContentSizeCategory = true } // MARK: - Inits override init(frame: CGRect) { super.init(frame: .zero) setupLayout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() heroImageView.image = nil fallbackFaviconImage.image = nil itemTitle.text = nil setFallBackFaviconVisibility(isHidden: false) } override func layoutSubviews() { super.layoutSubviews() rootContainer.layer.shadowPath = UIBezierPath(roundedRect: rootContainer.bounds, cornerRadius: HomepageViewModel.UX.generalCornerRadius).cgPath } func configure(viewModel: RecentlySavedCellViewModel, theme: Theme) { configureImages(heroImage: viewModel.heroImage, favIconImage: viewModel.favIconImage) itemTitle.text = viewModel.site.title applyTheme(theme: theme) } private func configureImages(heroImage: UIImage?, favIconImage: UIImage?) { if heroImage == nil { // Sets a small favicon in place of the hero image in case there's no hero image fallbackFaviconImage.image = favIconImage } else if heroImage?.size.width == heroImage?.size.height { // If hero image is a square use it as a favicon fallbackFaviconImage.image = heroImage } else { setFallBackFaviconVisibility(isHidden: true) heroImageView.image = heroImage } } private func setFallBackFaviconVisibility(isHidden: Bool) { fallbackFaviconBackground.isHidden = isHidden fallbackFaviconImage.isHidden = isHidden heroImageView.isHidden = !isHidden } // MARK: - Helpers private func setupLayout() { contentView.backgroundColor = .clear fallbackFaviconBackground.addSubviews(fallbackFaviconImage) imageContainer.addSubviews(heroImageView, fallbackFaviconBackground) rootContainer.addSubviews(imageContainer, itemTitle) contentView.addSubview(rootContainer) NSLayoutConstraint.activate([ rootContainer.topAnchor.constraint(equalTo: contentView.topAnchor), rootContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), rootContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), rootContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), // Image container, hero image and fallback imageContainer.topAnchor.constraint(equalTo: rootContainer.topAnchor, constant: UX.containerSpacing), imageContainer.leadingAnchor.constraint(equalTo: rootContainer.leadingAnchor, constant: UX.containerSpacing), imageContainer.trailingAnchor.constraint(equalTo: rootContainer.trailingAnchor, constant: -UX.containerSpacing), imageContainer.heightAnchor.constraint(equalToConstant: UX.heroImageSize.height), imageContainer.widthAnchor.constraint(equalToConstant: UX.heroImageSize.width), heroImageView.topAnchor.constraint(equalTo: imageContainer.topAnchor), heroImageView.leadingAnchor.constraint(equalTo: imageContainer.leadingAnchor), heroImageView.trailingAnchor.constraint(equalTo: imageContainer.trailingAnchor), heroImageView.bottomAnchor.constraint(equalTo: imageContainer.bottomAnchor), itemTitle.topAnchor.constraint(equalTo: heroImageView.bottomAnchor, constant: UX.generalSpacing), itemTitle.leadingAnchor.constraint(equalTo: heroImageView.leadingAnchor), itemTitle.trailingAnchor.constraint(equalTo: heroImageView.trailingAnchor), itemTitle.bottomAnchor.constraint(equalTo: rootContainer.bottomAnchor, constant: -UX.generalSpacing), fallbackFaviconBackground.centerXAnchor.constraint(equalTo: imageContainer.centerXAnchor), fallbackFaviconBackground.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor), fallbackFaviconBackground.heightAnchor.constraint(equalToConstant: UX.heroImageSize.height), fallbackFaviconBackground.widthAnchor.constraint(equalToConstant: UX.heroImageSize.width), fallbackFaviconImage.heightAnchor.constraint(equalToConstant: UX.fallbackFaviconSize.height), fallbackFaviconImage.widthAnchor.constraint(equalToConstant: UX.fallbackFaviconSize.width), fallbackFaviconImage.centerXAnchor.constraint(equalTo: fallbackFaviconBackground.centerXAnchor), fallbackFaviconImage.centerYAnchor.constraint(equalTo: fallbackFaviconBackground.centerYAnchor), itemTitle.topAnchor.constraint(equalTo: heroImageView.bottomAnchor, constant: UX.generalSpacing), itemTitle.leadingAnchor.constraint(equalTo: heroImageView.leadingAnchor), itemTitle.trailingAnchor.constraint(equalTo: heroImageView.trailingAnchor), itemTitle.bottomAnchor.constraint(equalTo: rootContainer.bottomAnchor, constant: -UX.generalSpacing) ]) } private func setupShadow(theme: Theme) { rootContainer.layer.shadowPath = UIBezierPath(roundedRect: rootContainer.bounds, cornerRadius: HomepageViewModel.UX.generalCornerRadius).cgPath rootContainer.layer.shadowColor = theme.colors.shadowDefault.cgColor rootContainer.layer.shadowOpacity = HomepageViewModel.UX.shadowOpacity rootContainer.layer.shadowOffset = HomepageViewModel.UX.shadowOffset rootContainer.layer.shadowRadius = HomepageViewModel.UX.shadowRadius } } // MARK: - ThemeApplicable extension RecentlySavedCell: ThemeApplicable { func applyTheme(theme: Theme) { itemTitle.textColor = theme.colors.textPrimary fallbackFaviconBackground.backgroundColor = theme.colors.layer1 fallbackFaviconBackground.layer.borderColor = theme.colors.layer1.cgColor adjustBlur(theme: theme) } } // MARK: - Blurrable extension RecentlySavedCell: Blurrable { func adjustBlur(theme: Theme) { // If blur is disabled set background color if shouldApplyWallpaperBlur { rootContainer.addBlurEffectWithClearBackgroundAndClipping(using: .systemThickMaterial) } else { rootContainer.removeVisualEffectView() rootContainer.backgroundColor = theme.colors.layer5 setupShadow(theme: theme) } } }
034f49d642694030935d74f0665f96bc
44.133005
116
0.68413
false
false
false
false
aquarchitect/MyKit
refs/heads/master
Sources/iOS/Extensions/UIKit/UICollectionViewFlowLayout+.swift
mit
1
// // UICollectionViewFlowLayout+.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2017 Hai Nguyen. // import UIKit public extension UICollectionViewFlowLayout { func delegateInsetForSection(at section: Int) -> UIEdgeInsets? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, insetForSectionAt: section) } func delegateMinimumLineSpacingForSection(at section: Int) -> CGFloat? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, minimumLineSpacingForSectionAt: section) } func delegateMinimumInteritemSpacingForSection(at section: Int) -> CGFloat? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, minimumInteritemSpacingForSectionAt: section) } func delegateReferenceSizeForHeader(in section: Int) -> CGSize? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, referenceSizeForHeaderInSection: section) } func delegateReferenceSizeForFooter(in section: Int) -> CGSize? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, referenceSizeForFooterInSection: section) } func delegateSizeForCell(at indexPath: IndexPath) -> CGSize? { guard let collectionView = self.collectionView else { return nil } return collectionView.delegate .flatMap({ $0 as? UICollectionViewDelegateFlowLayout })? .collectionView?(collectionView, layout: self, sizeForItemAt: indexPath) } } public extension UICollectionViewFlowLayout { /// Return an estimated number of elements that are visible /// in bounds by using known layout attributes including item size, /// section insets, spacing, and scroll direction. /// /// - Warning: the calculation is only capable of simple flow layout. @available(*, deprecated) var estimatedNumberOfVisibleElements: Int { guard let collectionView = self.collectionView else { return 0 } switch self.scrollDirection { case .vertical: return Int((collectionView.bounds.height - self.sectionInset.vertical + self.minimumLineSpacing) / (self.itemSize.height + self.minimumLineSpacing)) case .horizontal: return Int((collectionView.bounds.width - self.sectionInset.horizontal + self.minimumLineSpacing) / (self.itemSize.width + self.minimumInteritemSpacing)) } } }
86abd95c57b46490ce8bb772032659a7
40.2
165
0.68932
false
false
false
false
samwyndham/DictateSRS
refs/heads/master
DictateSRS/Shared/AlertPresenter.swift
mit
1
// // AlertPresenter.swift // DictateSRS // // Created by Sam Wyndham on 30/01/2017. // Copyright © 2017 Sam Wyndham. All rights reserved. // import UIKit /// Presents `UIAlertController`s without needing a `UIViewController` to /// present from class AlertPresenter { private var window: UIWindow? = nil /// Displays given `UIAlertController` in a new `UIWindow` /// /// Creates a window at `UIWindowLevelAlert` level and displays the given /// alert before destroying the window. If an alert is already displaying /// presenting a new alert does nothing. func presentAlert(_ alert: UIAlertController) { guard self.window == nil else { print("Attemped to show alert when existing alert is displayed") return } let vc = AlertPresenterViewController() vc.view.backgroundColor = UIColor.clear vc.didDismiss = { [unowned self] in self.window = nil } let window = UIWindow(frame: UIScreen.main.bounds) window.windowLevel = UIWindowLevelAlert window.backgroundColor = UIColor.clear window.rootViewController = vc window.makeKeyAndVisible() self.window = window window.rootViewController!.present(alert, animated: true, completion: nil) } } private class AlertPresenterViewController: UIViewController { var didDismiss: (() -> Void)? = nil override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { super.dismiss(animated: flag) { [unowned self] in completion?() self.didDismiss?() } } }
72334b5db999407a352a4496b9b00598
30.566038
82
0.633592
false
false
false
false
gp09/Beefit
refs/heads/master
BeefitMsc/BeefitMsc/BeeKeychainService.swift
mit
1
// // KeychainService.swift // Beefit // // Created by Priyank on 22/07/2017. // Copyright © 2017 priyank. All rights reserved. // import Foundation import Security // Constant Identifiers let userAccount = "AuthenticatedUser" let accessGroup = "SecuritySerivice" /** * User defined keys for new entry * Note: add new keys for new secure item and use them in load and save methods */ let passwordKey = "KeyForPassword" // Arguments for the keychain queries let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) public class BeeKeychainService: NSObject { /** * Exposed methods to perform save and load queries. */ public class func saveToken(token: NSString) { self.save(service: passwordKey as NSString, data: token) } public class func loadToken() -> NSString? { return self.load(service: passwordKey as NSString) } /** * Internal methods for querying the keychain. */ private class func save(service: NSString, data: NSString) { let dataFromString: NSData = data.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)! as NSData // Instantiate a new default keychain query let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue]) // Delete any existing items SecItemDelete(keychainQuery as CFDictionary) // Add the new keychain item SecItemAdd(keychainQuery as CFDictionary, nil) } private class func load(service: NSString) -> NSString? { // Instantiate a new default keychain query // Tell the query to return a result // Limit our results to one item let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue]) var dataTypeRef :AnyObject? // Search for the keychain items let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef) var contentsOfKeychain: NSString? = nil if status == errSecSuccess { if let retrievedData = dataTypeRef as? NSData { contentsOfKeychain = NSString(data: retrievedData as Data, encoding: String.Encoding.utf8.rawValue) } } else { print("Nothing was retrieved from the keychain. Status code \(status)") } return contentsOfKeychain } }
59163a3f78e6afc37cf75f8bf5039b60
35.977011
285
0.705316
false
false
false
false
salesforce-ux/design-system-ios
refs/heads/master
Demo-Swift/slds-sample-app/library/model/ApplicationModel.swift
bsd-3-clause
1
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit class ApplicationModel: NSObject { static let sharedInstance = ApplicationModel() var showSwift : Bool = true // MARK: Color data management //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var backgroundColors : Array<ColorObject> { return self.colorsFor(.background, first: SLDSBackgroundColorTypeFirst, last: SLDSBackgroundColorTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var borderColors : Array<ColorObject> { return self.colorsFor(.border, first: SLDSBorderColorTypeFirst, last:SLDSBorderColorTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var fillColors : Array<ColorObject> { return self.colorsFor(.fill, first: SLDSFillTypeFirst, last:SLDSFillTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var textColors : Array<ColorObject> { return self.colorsFor(.text, first: SLDSTextColorTypeFirst, last: SLDSTextColorTypeLast) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– private func sortHue ( c1: ColorObject, c2: ColorObject ) -> Bool { var h1:CGFloat = 0.0 var s1:CGFloat = 0.0 var b1:CGFloat = 0.0 var a1:CGFloat = 0.0 var h2:CGFloat = 0.0 var s2:CGFloat = 0.0 var b2:CGFloat = 0.0 var a2:CGFloat = 0.0 c1.color?.getHue(&h1, saturation: &s1, brightness: &b1, alpha: &a1) c2.color?.getHue(&h2, saturation: &s2, brightness: &b2, alpha: &a2) if a1 >= a2 - 0.05 || a1 < a2 + 0.05 { if h1 == h2 { if s1 >= s2 - 0.05 || s1 < s2 + 0.05 { return b2 < b1 } else { return s1 < s2 } } else { return h1 < h2 } } else { return a1 < a2 } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– private func colorsFor(_ type: ColorObjectType, first:NSInteger, last:NSInteger ) -> Array<ColorObject> { var colorList = Array<ColorObject>() for index in first...last { let color = ColorObject(type: type, index: index) colorList.append(color) } return colorList.sorted(by: self.sortHue) } // MARK: Icon data management //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var actionIcons : Array<IconObject> { return self.iconsFor( .action, first: SLDSActionIconTypeFirst, last: SLDSActionIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var customIcons : Array<IconObject> { return self.iconsFor( .custom, first: SLDSCustomIconTypeFirst, last: SLDSCustomIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var standardIcons : Array<IconObject> { return self.iconsFor( .standard, first: SLDSStandardIconTypeFirst, last: SLDSStandardIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var utilityIcons : Array<IconObject> { return self.iconsFor( .utility, first: SLDSUtilityIconTypeFirst, last: SLDSUtilityIconTypeLast ) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– private func iconsFor(_ type : IconObjectType, first:NSInteger, last:NSInteger ) -> Array<IconObject> { var iconList = Array<IconObject>() for index in first...last { let icon = IconObject(type: type, index: index, size: SLDSSquareIconMedium) iconList.append(icon) } return iconList } }
209768c7fe9a2e2bbed20e4927be8549
33.77686
114
0.453184
false
false
false
false
aijaz/icw1502
refs/heads/master
playgrounds/Week03.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Cocoa let person = "Swift Programmer" let person2:String person2 = "Aijaz" let shouldRun:Bool shouldRun = true let travel: String if shouldRun { travel = "run" } else { travel = "walk" } print ("I am going to \(travel)") // Perfectly good use of a var variable func hello(name: String, numberOfTimes: Int) -> String { var tempGreeting = "" for _ in 1 ... numberOfTimes { tempGreeting += "Hello, \(name)!\n" } return tempGreeting } hello("Aijaz", numberOfTimes: 5) let five = 5 let threepointfour = 3.4 let simpleProduct = 5 * 3.4 //let product = five * threepointfour let workingProduct = Double(five) * threepointfour let i1 = 5 //i1 = nil var name:String? name = "Aijaz" name = nil name = "Aijaz" print(name) print(name!) name = nil print (name) name = "aijaz" if name != nil { print (name!) } else { print ("No name given") } if let validName = name { print (validName) } else { print ("No name given") }
2e1d2771ff0d51c0503b259337f3c503
10.593407
56
0.63128
false
false
false
false
hooman/SwiftMath
refs/heads/master
Sources/Algorithms.swift
apache-2.0
1
// // Algorithms.swift // SwiftMath // // Global functions (public in internal) defined by SwiftMath module. // (c) 2016 Hooman Mehr. Licensed under Apache License v2.0 with Runtime Library Exception // /// Returns the Greatest Common Divisor (GCD) of two non-negative integers /// /// For convenience, assumes gcd(0,0) == 0 /// Implemented using "binary GCD algorithm" (aka Stein's algorithm) /// /// - Precondition: `a >= 0 && b >= 0` public func gcd(_ a: Int, _ b: Int) -> Int { assert(a >= 0 && b >= 0) // Assuming gcd(0,0)=0: guard a != 0 else { return b } guard b != 0 else { return a } var a = a, b = b, n = Int() //FIXME: Shift loops are slow and should be opimized. // Remove the largest 2ⁿ from them: while (a | b) & 1 == 0 { a >>= 1; b >>= 1; n += 1 } // Reduce `a` to odd value: while a & 1 == 0 { a >>= 1 } repeat { // Reduce `b` to odd value while b & 1 == 0 { b >>= 1 } // Both `a` & `b` are odd here (or zero maybe?) // Make sure `b` is greater if a > b { swap(&a, &b) } // Subtract smaller odd `a` from the bigger odd `b`, // which always gives a positive even number (or zero) b -= a // keep repeating this, until `b` reaches zero } while b != 0 return a << n // 2ⁿ×a } /// Returns the Greatest Common Divisor (GCD) of two unsigned integers /// /// For convenience, assumes gcd(0,0) == 0 /// Implemented using "binary GCD algorithm" (aka Stein's algorithm) public func gcd(_ a: UInt, _ b: UInt) -> UInt { // Assuming gcd(0,0)=0: guard a != 0 else { return b } guard b != 0 else { return a } var a = a, b = b, n = UInt() //FIXME: Shift loops are slow and should be opimized. // Remove the largest 2ⁿ from them: while (a | b) & 1 == 0 { a >>= 1; b >>= 1; n += 1 } // Reduce `a` to odd value: while a & 1 == 0 { a >>= 1 } repeat { // Reduce `b` to odd value while b & 1 == 0 { b >>= 1 } // Both `a` & `b` are odd here (or zero maybe?) // Make sure `b` is greater if a > b { swap(&a, &b) } // Subtract smaller odd `a` from the bigger odd `b`, // which always gives a positive even number (or zero) b -= a // keep repeating this, until `b` reaches zero } while b != 0 return a << n // 2ⁿ×a }
09650d37966a3832e14845d53c3851b3
25.041237
91
0.505542
false
false
false
false
danteteam/ProLayer
refs/heads/master
ProLayer/ProLayer.swift
mit
1
// // Builder.swift // GuessPointApp // // Created by Ivan Brazhnikov on 19.08.15. // Copyright (c) 2015 Ivan Brazhnikov. All rights reserved. // import UIKit public func Layer(layer: CALayer) -> ProLayer { return ProLayer(layer) } public func Layer(view: UIView) -> ProLayer { return ProLayer(view.layer) } public class ProLayer { let layer: CALayer init(_ layer: CALayer) { self.layer = layer } public func radius(value: CGFloat) -> Self { layer.cornerRadius = value return self } public func shadow() -> Shadow { return Shadow(buider: self) } public func border() -> Border { return Border(buider: self) } public class Border { private let parent: ProLayer private var layer: CALayer { return parent.layer } init(buider: ProLayer) { self.parent = buider } public func color(value: UIColor) -> Self { layer.borderColor = value.CGColor return self } public func width(value: CGFloat) -> Self { layer.borderWidth = value return self } public func done() -> ProLayer { return parent } } public class Shadow { private let parent: ProLayer private var layer: CALayer { return parent.layer } init(buider: ProLayer) { self.parent = buider } public func color(value: UIColor) -> Self { layer.shadowColor = value.CGColor return self } public func radius(value: CGFloat) -> Self { layer.shadowRadius = value return self } public func opacity(value: Float) -> Self { layer.shadowOpacity = value return self } public func offset(value: CGSize) -> Self { layer.shadowOffset = value return self } public func path(value: CGPath) -> Self { layer.shadowPath = value return self } public func done() -> ProLayer { return parent } } }
b26c277e9c37cf37783a0cd4ad8b8bf4
21.49505
60
0.521356
false
false
false
false
gitgitcode/LearnSwift
refs/heads/master
Calculator/Caiculator/Caiculator/ViewController.swift
apache-2.0
1
// // ViewController.swift // Caiculator // // Created by xuthus on 15/6/14. // Copyright (c) 2015年 xuthus. All rights reserved. // import UIKit class ViewController: UIViewController { //定义了一个类 //有针对的名字 单继承 @IBOutlet weak var display: UILabel! //prop !是 类型 未定义 var userIsInTheMiddletofTypingANumbser: Bool = false @IBAction func appendDigit(sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddletofTypingANumbser { display.text = display.text! + digit }else{ display.text = digit userIsInTheMiddletofTypingANumbser = true } println("digit = \(digit)") } @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddletofTypingANumbser { enter() } switch operation { case "×": performOperation{$0 * $1} case "÷": performOperation{$1 / $0} case "+": performOperation{$0 + $1} case "−": performOperation{$1 - $0} default:break } } func performOperation(operation:(Double,Double) ->Double){ if operandStack.count >= 2 { //displayValue = operandStack.removeLast() * operandStack.removeLast() displayValue = operation(operandStack.removeLast(),operandStack.removeLast()) enter() } } // var operandStack: Array<Double> = Array<Double>() var operandStack = Array<Double>() @IBAction func enter() { userIsInTheMiddletofTypingANumbser = false operandStack.append(displayValue) println("operandStack = \(operandStack)") } //转化设置dipaly的值 var displayValue: Double { get { return NSNumberFormatter().numberFromString(display.text!)!.doubleValue } set { //double -> string display.text = "\(newValue)" userIsInTheMiddletofTypingANumbser = false } } }
52f02925113431791cb6e804c3c27d58
25.818182
89
0.580145
false
false
false
false
farzadshbfn/POP
refs/heads/master
Sources/SegueHandlerType.swift
mit
1
// // SegueHandlerType.swift // POP // // Created by Farzad Sharbafian on 1/8/17. // Copyright © 2017 FarzadShbfn. All rights reserved. // import Foundation import UIKit public protocol SegueHandlerType { associatedtype SegueIdentifier: RawRepresentable } extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String { public func performSegue(withSegueIdentifier segue: SegueIdentifier, sender: Any?) { performSegue(withIdentifier: segue.rawValue, sender: sender) } public func segueIdentifier(forSegue segue: UIStoryboardSegue) -> SegueIdentifier { guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else { fatalError("Invalid segue identifier \(segue.identifier) for view controller of type \(type(of: self)).") } return segueIdentifier } public func destination<T: UIViewController>(forSegue segue: UIStoryboardSegue) -> T { guard let viewController = segue.destination as? T else { fatalError("Invalid Destination ViewController: \(T.self) bounded to Segue: \(segueIdentifier(forSegue: segue)), ") } return viewController } }
def19e069fc1c6798c5346328b416bd2
29.5
118
0.759275
false
false
false
false
schibsted/layout
refs/heads/master
Layout/LayoutError.swift
mit
1
// Copyright © 2017 Schibsted. All rights reserved. import Foundation private func stringify(_ error: Error) -> String { switch error { case is SymbolError, is LayoutError, is FileError, is XMLParser.Error, is Expression.Error: return "\(error)" default: return error.localizedDescription } } /// An error relating to a specific symbol/expression internal struct SymbolError: Error, CustomStringConvertible { let symbol: String let error: Error var fatal = false init(_ error: Error, for symbol: String) { self.symbol = symbol if let error = error as? SymbolError { let description = error.description if symbol == error.symbol || description.contains(symbol) { self.error = error.error } else if description.contains(error.symbol) { self.error = SymbolError(description, for: error.symbol) } else { self.error = SymbolError("\(description) for \(error.symbol)", for: error.symbol) } } else { self.error = error } } /// Creates an error for the specified symbol init(_ message: String, for symbol: String) { self.init(Expression.Error.message(message), for: symbol) } /// Creates a fatal error for the specified symbol init(fatal message: String, for symbol: String) { self.init(Expression.Error.message(message), for: symbol) fatal = true } public var description: String { var description = stringify(error) if !description.contains(symbol) { description = "\(description) in \(symbol) expression" } return description } /// Associates error thrown by the wrapped closure with the given symbol static func wrap<T>(_ closure: () throws -> T, for symbol: String) throws -> T { do { return try closure() } catch { throw self.init(error, for: symbol) } } } /// The public interface for all Layout errors public enum LayoutError: Error, Hashable, CustomStringConvertible { case message(String) case generic(Error, String?) case unknownExpression(Error /* SymbolError */, [String]) case unknownSymbol(Error /* SymbolError */, [String]) case multipleMatches([URL], for: String) public init?(_ error: Error?) { guard let error = error else { return nil } self.init(error) } public init(_ message: String, in className: String? = nil, in url: URL? = nil) { self.init(LayoutError.message(message), in: className, in: url) } @available(*, deprecated, message: "Use init(_:in:) instead") public init(_ message: String, for viewOrControllerClass: AnyClass?) { self.init(message, in: viewOrControllerClass.map(nameOfClass)) } public init(_ error: Error, in className: String?, in url: URL?) { self = .generic(LayoutError(error, in: className), url?.lastPathComponent) } public init(_ error: Error, in classNameOrFile: String?) { if let cls: AnyClass = classNameOrFile.flatMap(classFromString) { self.init(error, for: cls) } else { self.init(LayoutError.generic(error, classNameOrFile)) } } public init(_ error: Error, for viewOrControllerClass: AnyClass? = nil) { switch error { case LayoutError.multipleMatches: // Should never be wrapped or it's hard to treat as special case self = error as! LayoutError case let LayoutError.generic(_, cls) where cls == viewOrControllerClass.map(nameOfClass): self = error as! LayoutError case let error as LayoutError where viewOrControllerClass == nil: self = error default: self = .generic(error, viewOrControllerClass.map(nameOfClass)) } } public var suggestions: [String] { switch self { case let .unknownExpression(_, suggestions), let .unknownSymbol(_, suggestions): return suggestions case let .generic(error, _): return (error as? LayoutError)?.suggestions ?? [] default: return [] } } public var description: String { switch self { case let .message(message): return message case let .generic(error, className): var description = stringify(error) if let className = className { if !description.contains(className) { description = "\(description) in \(className)" } } return description case let .unknownExpression(error, _), let .unknownSymbol(error, _): return stringify(error) case let .multipleMatches(_, path): return "Layout found multiple source files matching \(path)" } } // Returns true if the error can be cleared, or false if the // error is fundamental, and requires a code change + reload to fix it public var isTransient: Bool { switch self { case let .generic(error, _), let .unknownSymbol(error, _), let .unknownExpression(error, _): if let error = error as? LayoutError { return error.isTransient } return (error as? SymbolError)?.fatal != true case .multipleMatches, _ where description.contains("XML"): // TODO: less hacky return false default: return true // TODO: handle expression parsing errors } } public func hash(into hasher: inout Hasher) { description.hash(into: &hasher) } public static func == (lhs: LayoutError, rhs: LayoutError) -> Bool { return lhs.description == rhs.description } /// Converts error thrown by the wrapped closure to a LayoutError static func wrap<T>(_ closure: () throws -> T) throws -> T { return try wrap(closure, in: nil) } static func wrap<T>(_ closure: () throws -> T, in className: String?, in url: URL? = nil) throws -> T { do { return try closure() } catch { throw self.init(error, in: className, in: url) } } }
e2ff33472b72255a1f8ace94bd099dd0
32.673684
107
0.589403
false
false
false
false
vito5314/RSSwift
refs/heads/master
RSSwift/RSSwift/FeedTableViewController.swift
apache-2.0
1
// // FeedTableViewController.swift // RSSwift // // Created by Arled Kola on 20/09/2014. // Copyright (c) 2014 Arled. All rights reserved. // import UIKit class FeedTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, NSXMLParserDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! var myFeed : NSArray = [] var url: NSURL = NSURL() override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { menuButton.target=self.revealViewController() menuButton.action="revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } // Cell height. self.tableView.rowHeight = 70 self.tableView.dataSource = self self.tableView.delegate = self // Set feed url. http://www.formula1.com/rss/news/latest.rss url = NSURL(string: "http://www.skysports.com/rss/0,20514,11661,00.xml")! // Call custom function. loadRss(url); } func loadRss(data: NSURL) { // XmlParserManager instance/object/variable var myParser : XmlParserManager = XmlParserManager.alloc().initWithURL(data) as! XmlParserManager // Put feed in array myFeed = myParser.feeds tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let newUrl = segue.destinationViewController as? NewFeedViewController { newUrl.onDataAvailable = {[weak self] (data) in if let weakSelf = self { weakSelf.loadRss(data) } } } else if segue.identifier == "openPage" { var indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow()! //let selectedFeedURL: String = feeds[indexPath.row].objectForKey("link") as String let selectedFTitle: String = myFeed[indexPath.row].objectForKey("title") as! String let selectedFContent: String = myFeed[indexPath.row].objectForKey("description") as! String let selectedFURL: String = myFeed[indexPath.row].objectForKey("link") as! String // Instance of our feedpageviewcontrolelr let fpvc: FeedPageViewController = segue.destinationViewController as! FeedPageViewController fpvc.selectedFeedTitle = selectedFTitle fpvc.selectedFeedFeedContent = selectedFContent fpvc.selectedFeedURL = selectedFURL } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myFeed.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell // Feeds dictionary. var dict : NSDictionary! = myFeed.objectAtIndex(indexPath.row) as! NSDictionary // Set cell properties. cell.textLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("title") as? String cell.detailTextLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("pubDate") as? String return cell } }
32047f79db4f3027a2a66bf54e88b220
33.915094
119
0.641989
false
false
false
false
Eonil/EditorLegacy
refs/heads/trial1
Modules/SwiftCodeGeneration/Sources/Syntax.swift
mit
1
// // SwiftCodeGeneration3.swift // DataConverterClassGenerator // // Created by Hoon H. on 11/16/14. // // import Foundation public typealias Statements = NodeList<Statement> public enum Statement : NodeType { case Expression(SwiftCodeGeneration.Expression) case Declaration(SwiftCodeGeneration.Declaration) case LoopStatement(SwiftCodeGeneration.LoopStatement) public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Expression(let s): s.writeTo(&w) case .Declaration(let s): s.writeTo(&w) case .LoopStatement(let s): s.writeTo(&w) } w.writeToken(";") } } public enum LoopStatement : NodeType { // case ForStatement case ForInStatement(pattern:Pattern, expression:Expression, codeBlock:CodeBlock) // case WhileStatement // case DoWhileStatement public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .ForInStatement(let s): w <<< "for" ~ s.pattern ~ "in" ~ s.expression ~ s.codeBlock } } } public struct Pattern : NodeType { public var text:String public func writeTo<C:CodeWriterType>(inout w:C) { w.writeToken(text) } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/code-block public struct CodeBlock : NodeType { public var statements : Statements public init() { self.statements = Statements() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< "{" ~ statements ~ "}" } } public enum ForInStatement { public func writeTo<C : CodeWriterType>(inout w: C) { } } public enum Expression : NodeType { public func writeTo<C : CodeWriterType>(inout w: C) { } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/declaration public enum Declaration : NodeType { case Import(ImportDeclaration) // case Constant case Variable(VariableDeclaration) // case Typealias case Function(FunctionDeclaration) // case Enum case Struct(StructDeclaration) case Class(ClassDeclaration) // case Protocol case Initializer(InitializerDeclaration) // case Deinitializer case Extension(ExtensionDeclaration) // case Subscript(SubscriptDeclaration) // case Operator public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Import(let s): w <<< s case .Variable(let s): w <<< s case .Function(let s): w <<< s case .Struct(let s): w <<< s case .Class(let s): w <<< s case .Initializer(let s): w <<< s case .Extension(let s): w <<< s } } } public typealias Declarations = NodeList<Declaration> public struct ImportDeclaration: NodeType { public var attributes : Attributes public var importKind : String public var importPath : String public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ importKind ~ importPath } } /// Simplified. public struct VariableDeclaration: NodeType { public var variableDeclarationHead : VariableDeclarationHead public var name : String public var type : Type public init(name:String, type:String) { self.variableDeclarationHead = VariableDeclarationHead(attributes: Attributes(), declarationModifiers: DeclarationModifier.AccessLevel(AccessLevelModifier.Internal)) self.name = name self.type = Type(text: type) } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< variableDeclarationHead w.writeToken(name) w.writeToken(":") w <<< type } } public struct VariableDeclarationHead: NodeType { public var attributes : Attributes public var declarationModifiers : DeclarationModifier public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ declarationModifiers ~ "var" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/function-declaration public struct FunctionDeclaration: NodeType { var functionHead : FunctionHead var functionName : FunctionName var genericParameterClause : GenericParameterClause? var functionSignature : FunctionSignature var functionBody : FunctionBody /// Creates `()->()` function. public init(name:String) { self.init(name: name, resultType: "()") } /// Creates `()->T` function. public init(name:String, resultType:String) { self.init(name: name, inputParameters: ParameterList(), resultType: resultType) } /// Creates `T->T` function. public init(name:String, inputParameters:ParameterList, resultType:String) { self.functionHead = FunctionHead(attributes: Attributes(), declarationModifiers: DeclarationModifiers()) self.functionName = FunctionName.Identifier(Identifier(name)) self.genericParameterClause = GenericParameterClause(dummy: "") self.functionSignature = FunctionSignature(parameterClauses: ParameterClauses([ParameterClause(parameters: inputParameters, variadic: false)]), functionResult: FunctionResult(attributes: Attributes(), type: Type(text: resultType))) self.functionBody = FunctionBody() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< functionHead ~ functionName ~ genericParameterClause ~ functionSignature ~ functionBody } } public struct FunctionHead: NodeType { var attributes : Attributes var declarationModifiers : DeclarationModifiers public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ declarationModifiers ~ "func" } } public enum FunctionName: NodeType { case Identifier(SwiftCodeGeneration.Identifier) // case Operator public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Identifier(let s): w.writeToken(s) } } } public struct FunctionSignature: NodeType { public var parameterClauses : ParameterClauses public var functionResult : FunctionResult public func writeTo<C : CodeWriterType>(inout w: C) { w <<< parameterClauses ~ functionResult } } public struct FunctionResult: NodeType { var attributes : Attributes var type : Type public func writeTo<C : CodeWriterType>(inout w: C) { w <<< "->" ~ attributes ~ type } } public struct FunctionBody: NodeType { public var codeBlock : CodeBlock public init() { self.codeBlock = CodeBlock() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< codeBlock } } public struct StructDeclaration: NodeType { public var attributes : Attributes? public var accessLevelModifier : AccessLevelModifier? public var structName : Identifier public var genericParameterClause : GenericParameterClause? public var typeInheritanceClause : TypeInheritanceClause? public var structBody : Declarations public init(name:String) { self.structName = Identifier(name) self.structBody = Declarations() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ accessLevelModifier ~ "struct" ~ structName ~ genericParameterClause ~ typeInheritanceClause ~ "{" ~ structBody ~ "}" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/class-declaration public struct ClassDeclaration: NodeType { public var attributes : Attributes? public var accessLevelModifier : AccessLevelModifier? public var className : Identifier public var genericParameterClause : GenericParameterClause? public var typeInheritanceClause : TypeInheritanceClause? public var classBody : Declarations public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ accessLevelModifier ~ "class" ~ className ~ genericParameterClause ~ typeInheritanceClause ~ "{" ~ classBody ~ "}" } } // enum ImportKind: NodeType { // public func writeTo<C : CodeWriterType>(inout w: C) { // } // } public struct Attribute: NodeType { public func writeTo<C : CodeWriterType>(inout w: C) { } } public typealias Attributes = NodeList<Attribute> /// Disabled due to compiler bug. public enum AccessLevelModifier: NodeType { case Internal case InternalSet case Private case PrivateSet case Public case PublicSet public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .Internal: w.writeToken("internal") case .InternalSet: w.writeToken("internal ( set )") case .Private: w.writeToken("private") case .PrivateSet: w.writeToken("private ( set )") case .Public: w.writeToken("public") case .PublicSet: w.writeToken("public ( set )") } } } public struct GenericParameterClause: NodeType { public var dummy:String public func writeTo<C : CodeWriterType>(inout w: C) { } } // Simplified... too much of needless works. public typealias TypeInheritanceClause = String // public struct TypeInheritanceClause: NodeType { // public var dummy:String // public func writeTo<C : CodeWriterType>(inout w: C) { // } // } public struct StructBody: NodeType { public var declarations:Declarations public func writeTo<C : CodeWriterType>(inout w: C) { } } public struct ClassBody: NodeType { public var declarations:Declarations public func writeTo<C : CodeWriterType>(inout w: C) { } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/initializer-declaration public struct InitializerDeclaration: NodeType { public var initializerHead:InitializerHead public var genericParameterClause:GenericParameterClause? public var parameterClause:ParameterClause public var initializerBody:CodeBlock public init() { self.init(failable: false) } public init(failable:Bool) { self.init(failable: false, parameters: ParameterList()) } public init(failable:Bool, parameters:ParameterList) { self.initializerHead = InitializerHead(attributes: Attributes(), declarations: nil, failable: failable) self.parameterClause = ParameterClause(parameters: parameters, variadic: false) self.initializerBody = CodeBlock() } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< initializerHead ~ genericParameterClause ~ parameterClause ~ initializerBody } } public struct InitializerHead: NodeType { public var attributes : Attributes public var declarations : DeclarationModifiers? public var failable : Bool public func writeTo<C : CodeWriterType>(inout w: C) { w <<< attributes ~ declarations ~ "init" ~ (failable ? "?" : "") } } public enum DeclarationModifier: NodeType { case AccessLevel(AccessLevelModifier) // case Class // case Convenience // case Dynamic // case Final // case Infix // case Lazy // case Mutating // case NonMutating // case Optional // case Override // case Postfix // case Prefix // case Required // case Static // case Unowned // case UnownedSafe // case UnownedUnsafe // case Weak public func writeTo<C : CodeWriterType>(inout w: C) { switch self { case .AccessLevel(let s): w <<< s } } } public typealias DeclarationModifiers = NodeList<DeclarationModifier> /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/parameter-clause public struct ParameterClause: NodeType { public var parameters : ParameterList public var variadic : Bool public func writeTo<C : CodeWriterType>(inout w: C) { w <<< "(" ~ parameters ~ (variadic ? "..." : "") ~ ")" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/parameter-clauses public typealias ParameterClauses = NodeList<ParameterClause> public struct ParameterList: NodeType { public var items : [Parameter] public init() { items = [] } public func writeTo<C : CodeWriterType>(inout w: C) { for i in 0..<items.count { let m = items[i] w <<< m if i < items.count-1 { w.writeToken(",") } } } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/parameter public struct Parameter: NodeType { public var byref : Bool public var mutable : Bool public var hashsign : Bool public var externalParameterName : Identifier? public var localParameterName : Identifier public var typeAnnotation : TypeAnnotation public var defaultArgumentClause : Expression? // public var attributes = NodeList<Attribute>() // public var type : Type public init(name:String, type:String) { byref = false mutable = false hashsign = false localParameterName = Identifier(name) typeAnnotation = TypeAnnotation(attributes: Attributes(), type: Type(text: type)) } public func writeTo<C : CodeWriterType>(inout w: C) { w.writeToken(byref ? "inout" : "") w.writeToken(mutable ? "var" : "let") w.writeToken(hashsign ? "#" : "") if externalParameterName != nil { w.writeToken(externalParameterName!) } w.writeToken(localParameterName) w <<< typeAnnotation ~ defaultArgumentClause } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Types.html#//apple_ref/swift/grammar/type-annotation public struct TypeAnnotation: NodeType { public var attributes : Attributes? public var type : Type public func writeTo<C : CodeWriterType>(inout w: C) { w <<< ":" ~ attributes ~ type } } public struct Type: NodeType { public var text:String public func writeTo<C : CodeWriterType>(inout w: C) { w.writeToken(text) } } // enum Type: NodeType { //// case Array //// case Dictionary //// case Function // case TypeIdentifier(expression:String) //// case Tuple //// case Optional //// case ImplicitlyUnwrappedOptional //// case ProtocolCOmposition //// case Metatype // // public func writeTo<C : CodeWriterType>(inout w: C) { // switch self { // case .TypeIdentifier(let s): w.writeToken(s) // } // } // } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-XID_704 public struct ExtensionDeclaration: NodeType { public var accessLevelModifier:AccessLevelModifier? public var typeIdentifier:TypeIdentifier public var typeInheritanceClause:TypeInheritanceClause? public var extensionBody:Declarations public func writeTo<C : CodeWriterType>(inout w: C) { w <<< accessLevelModifier ~ typeInheritanceClause ~ "{" ~ extensionBody ~ "}" } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Types.html#//apple_ref/swift/grammar/type-identifier public struct TypeIdentifier: NodeType { public var typeName:Identifier public var genericArgumentClause:GenericArgumentClause? public var subtypeIdentifier:(()->TypeIdentifier)? public init(typeName:Identifier, genericArgumentClause:GenericArgumentClause?) { self.typeName = typeName self.genericArgumentClause = genericArgumentClause } public init(_ parts:[(typeName:Identifier, genericArgumentClause:GenericArgumentClause?)]) { precondition(parts.count >= 1) switch parts.count { case 0: fatalError("Bad input.") case 1: self.init(parts[0]) subtypeIdentifier = nil default: self.init(parts[0]) let a = TypeIdentifier(parts.rest.array) subtypeIdentifier = { a } } } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< typeName ~ genericArgumentClause if let x1 = subtypeIdentifier { w.writeToken(".") w <<< x1() } } } /// https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/GenericParametersAndArguments.html#//apple_ref/doc/uid/TP40014097-CH37-XID_872 public struct GenericArgumentClause: NodeType { public var genericArguments : Type public var additionalArgument : (()->GenericArgumentClause)? public init(_ argument:Type) { genericArguments = argument additionalArgument = nil } public init(_ arguments:[Type]) { precondition(arguments.count >= 1) genericArguments = arguments.first! if arguments.count > 1 { let rest = GenericArgumentClause(arguments.rest.array) additionalArgument = { rest } } additionalArgument = nil } public func writeTo<C : CodeWriterType>(inout w: C) { w <<< genericArguments if let a1 = additionalArgument { w.writeToken(",") w <<< a1() } } } //public struct SubscriptDeclaration { // //} public typealias Identifier = String
f448836dfc0cb6f496a212fdda6021e1
28.11032
234
0.734963
false
false
false
false
huangboju/QMUI.swift
refs/heads/master
QMUI.swift/QMUIKit/UIComponents/ImagePickerLibrary/QMUIImagePickerCollectionViewCell.swift
mit
1
// // QMUIImagePickerCollectionViewCell.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // // checkbox 的 margin 默认值 let QMUIImagePickerCollectionViewCellDefaultCheckboxButtonMargins = UIEdgeInsets(top: 6, left: 0, bottom: 0, right: 6) private let QMUIImagePickerCollectionViewCellDefaultVideoMarkImageViewMargins = UIEdgeInsets(top: 0, left: 8, bottom: 8, right: 0) /** * 图片选择空间里的九宫格 cell,支持显示 checkbox、饼状进度条及重试按钮(iCloud 图片需要) */ class QMUIImagePickerCollectionViewCell: UICollectionViewCell { /// checkbox 未被选中时显示的图片 var checkboxImage: UIImage! { didSet { if checkboxImage != oldValue { checkboxButton.setImage(checkboxImage, for: .normal) checkboxButton.sizeToFit() } } } /// checkbox 被选中时显示的图片 var checkboxCheckedImage: UIImage! { didSet { if checkboxCheckedImage != oldValue { checkboxButton.setImage(checkboxCheckedImage, for: .selected) checkboxButton.setImage(checkboxCheckedImage, for: [.selected, .highlighted]) checkboxButton.sizeToFit() } } } /// checkbox 的 margin,定位从每个 cell(即每张图片)的最右边开始计算 var checkboxButtonMargins = QMUIImagePickerCollectionViewCellDefaultCheckboxButtonMargins /// videoMarkImageView 的 icon var videoMarkImage: UIImage! = QMUIHelper.image(name: "QMUI_pickerImage_video_mark") { didSet { if videoMarkImage != oldValue { videoMarkImageView?.image = videoMarkImage videoMarkImageView?.sizeToFit() } } } /// videoMarkImageView 的 margin,定位从每个 cell(即每张图片)的左下角开始计算 var videoMarkImageViewMargins: UIEdgeInsets = QMUIImagePickerCollectionViewCellDefaultVideoMarkImageViewMargins /// videoDurationLabel 的字号 var videoDurationLabelFont: UIFont = UIFontMake(12) { didSet { if videoDurationLabelFont != oldValue { videoDurationLabel?.font = videoDurationLabelFont videoDurationLabel?.qmui_calculateHeightAfterSetAppearance() } } } /// videoDurationLabel 的字体颜色 var videoDurationLabelTextColor: UIColor = UIColorWhite { didSet { if videoDurationLabelTextColor != oldValue { videoDurationLabel?.textColor = videoDurationLabelTextColor } } } /// videoDurationLabel 布局是对齐右下角再做 margins 偏移 var videoDurationLabelMargins: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 6, right: 6) private(set) var contentImageView: UIImageView! private(set) var checkboxButton: UIButton! private var _videoMarkImageView: UIImageView? var videoMarkImageView: UIImageView? { initVideoRelatedViewsIfNeeded() return _videoMarkImageView } private var _videoDurationLabel: UILabel? var videoDurationLabel: UILabel? { initVideoRelatedViewsIfNeeded() return _videoDurationLabel } private var _videoBottomShadowLayer: CAGradientLayer? var videoBottomShadowLayer: CAGradientLayer? { initVideoRelatedViewsIfNeeded() return _videoBottomShadowLayer } var isSelectable: Bool = false { didSet { if downloadStatus == .succeed { checkboxButton.isHidden = !isSelectable } } } var isChecked: Bool = false { didSet { if isSelectable { checkboxButton.isSelected = isChecked QMUIImagePickerHelper.removeSpringAnimationOfImageChecked(with: checkboxButton) if isChecked { QMUIImagePickerHelper.springAnimationOfImageChecked(with: checkboxButton) } } } } // Cell 中对应资源的下载状态,这个值的变动会相应地调整 UI 表现 var downloadStatus: QMUIAssetDownloadStatus = .succeed { didSet { if isSelectable { checkboxButton.isHidden = !isSelectable } } } var assetIdentifier: String? // 当前这个 cell 正在展示的 QMUIAsset 的 identifier override init(frame: CGRect) { super.init(frame: frame) initImagePickerCollectionViewCellUI() } private func initImagePickerCollectionViewCellUI() { contentImageView = UIImageView() contentImageView.contentMode = .scaleAspectFill contentImageView.clipsToBounds = true contentView.addSubview(contentImageView) checkboxButton = QMUIButton() checkboxButton.qmui_automaticallyAdjustTouchHighlightedInScrollView = true checkboxButton.qmui_outsideEdge = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) checkboxButton.isHidden = true contentView.addSubview(checkboxButton) checkboxImage = QMUIHelper.image(name: "QMUI_pickerImage_checkbox") checkboxCheckedImage = QMUIHelper.image(name: "QMUI_pickerImage_checkbox_checked") } private func initVideoBottomShadowLayerIfNeeded() { if _videoBottomShadowLayer == nil { _videoBottomShadowLayer = CAGradientLayer() _videoBottomShadowLayer!.qmui_removeDefaultAnimations() _videoBottomShadowLayer!.colors = [ UIColor(r: 0, g: 0, b: 0).cgColor, UIColor(r: 0, g: 0, b: 0, a: 0.6).cgColor, ] contentView.layer.addSublayer(_videoBottomShadowLayer!) setNeedsLayout() } } private func initVideoMarkImageViewIfNeed() { if _videoMarkImageView != nil { return } _videoMarkImageView = UIImageView() _videoMarkImageView?.image = videoMarkImage _videoMarkImageView?.sizeToFit() contentView.addSubview(_videoMarkImageView!) setNeedsLayout() } private func initVideoDurationLabelIfNeed() { if _videoDurationLabel != nil { return } _videoDurationLabel = UILabel() _videoDurationLabel?.font = videoDurationLabelFont _videoDurationLabel?.textColor = videoDurationLabelTextColor contentView.addSubview(_videoDurationLabel!) setNeedsLayout() } private func initVideoRelatedViewsIfNeeded() { initVideoBottomShadowLayerIfNeeded() initVideoMarkImageViewIfNeed() initVideoDurationLabelIfNeed() } override func layoutSubviews() { super.layoutSubviews() contentImageView.frame = contentView.bounds if isSelectable { checkboxButton.frame = checkboxButton.frame.setXY(contentView.bounds.width - checkboxButtonMargins.right - checkboxButton.frame.width, checkboxButtonMargins.top) } if let videoBottomShadowLayer = _videoBottomShadowLayer, let videoMarkImageView = _videoMarkImageView, let videoDurationLabel = _videoDurationLabel { videoMarkImageView.frame = videoMarkImageView.frame.setXY(videoMarkImageViewMargins.left, contentView.bounds.height - videoMarkImageView.bounds.height - videoMarkImageViewMargins.bottom) videoDurationLabel.sizeToFit() let minX = contentView.bounds.width - videoDurationLabelMargins.right - videoDurationLabel.bounds.width let minY = contentView.bounds.height - videoDurationLabelMargins.bottom - videoDurationLabel.bounds.height videoDurationLabel.frame = videoDurationLabel.frame.setXY(minX, minY) let videoBottomShadowLayerHeight = contentView.bounds.height - videoMarkImageView.frame.minY + videoMarkImageViewMargins.bottom // 背景阴影遮罩的高度取决于(视频 icon 的高度 + 上下 margin) videoBottomShadowLayer.frame = CGRectFlat(0, contentView.bounds.height - videoBottomShadowLayerHeight, contentView.bounds.width, videoBottomShadowLayerHeight) } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } }
f133d054269a4791aabe86eb65b7d167
35.785388
198
0.65926
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Controllers/Preferences/Profile/EditProfileTableViewController.swift
mit
1
// // EditProfileTableViewController.swift // Rocket.Chat // // Created by Filipe Alvarenga on 27/02/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit import MBProgressHUD import SwiftyJSON // swiftlint:disable file_length type_body_length final class EditProfileTableViewController: BaseTableViewController, MediaPicker { static let identifier = String(describing: EditProfileTableViewController.self) @IBOutlet weak var statusValueLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! { didSet { statusLabel.text = viewModel.statusTitle } } @IBOutlet weak var name: UITextField! { didSet { name.placeholder = viewModel.namePlaceholder } } @IBOutlet weak var username: UITextField! { didSet { username.placeholder = viewModel.usernamePlaceholder } } @IBOutlet weak var email: UITextField! { didSet { email.placeholder = viewModel.emailPlaceholder } } @IBOutlet weak var changeYourPassword: UILabel! { didSet { changeYourPassword.text = viewModel.changeYourPasswordTitle } } @IBOutlet weak var avatarButton: UIButton! { didSet { avatarButton.accessibilityLabel = avatarButtonAccessibilityLabel } } var avatarView: AvatarView = { let avatarView = AvatarView() avatarView.isUserInteractionEnabled = false avatarView.translatesAutoresizingMaskIntoConstraints = false avatarView.layer.cornerRadius = 15 avatarView.layer.masksToBounds = true return avatarView }() lazy var activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView(style: .gray) activityIndicator.startAnimating() return activityIndicator }() let editingAvatarImage = UIImage(named: "Camera")?.imageWithTint(.RCEditingAvatarColor()) var editButton: UIBarButtonItem? var saveButton: UIBarButtonItem? var cancelButton: UIBarButtonItem? let api = API.current() var avatarFile: FileUpload? var authSettings: AuthSettings? { return AuthSettingsManager.shared.settings } var numberOfSections: Int { guard !isLoading else { return 0 } guard let authSettings = authSettings else { return 2 } return !authSettings.isAllowedToEditProfile || !authSettings.isAllowedToEditPassword ? 2 : 3 } var canEditAnyInfo: Bool { guard authSettings?.isAllowedToEditProfile ?? false, authSettings?.isAllowedToEditAvatar ?? false || authSettings?.isAllowedToEditName ?? false || authSettings?.isAllowedToEditUsername ?? false || authSettings?.isAllowedToEditEmail ?? false else { return false } return true } var isUpdatingUser = false var isUploadingAvatar = false var isLoading = true var currentPassword: String? var user: User? = User() { didSet { bindUserData() } } private let viewModel = EditProfileViewModel() // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)) tapGesture.cancelsTouchesInView = false tableView.addGestureRecognizer(tapGesture) editButton = UIBarButtonItem(title: viewModel.editButtonTitle, style: .plain, target: self, action: #selector(beginEditing)) saveButton = UIBarButtonItem(title: viewModel.saveButtonTitle, style: .done, target: self, action: #selector(saveProfile(_:))) cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(didPressCancelEditingButton)) navigationItem.title = viewModel.title disableUserInteraction() setupAvatarButton() fetchUserData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateUserStatus() } // MARK: Setup func setupAvatarButton() { avatarButton.addSubview(avatarView) avatarView.topAnchor.constraint(equalTo: avatarButton.topAnchor).isActive = true avatarView.bottomAnchor.constraint(equalTo: avatarButton.bottomAnchor).isActive = true avatarView.leadingAnchor.constraint(equalTo: avatarButton.leadingAnchor).isActive = true avatarView.trailingAnchor.constraint(equalTo: avatarButton.trailingAnchor).isActive = true if let imageView = avatarButton.imageView { avatarButton.bringSubviewToFront(imageView) } } func fetchUserData() { avatarButton.isHidden = true let fetchUserLoader = MBProgressHUD.showAdded(to: self.view, animated: true) fetchUserLoader.mode = .indeterminate let stopLoading = { self.avatarButton.isHidden = false fetchUserLoader.hide(animated: true) } let meRequest = MeRequest() api?.fetch(meRequest) { [weak self] response in stopLoading() switch response { case .resource(let resource): if let errorMessage = resource.errorMessage { Alert(key: "alert.load_profile_error").withMessage(errorMessage).present(handler: { _ in self?.navigationController?.popViewController(animated: true) }) } else { self?.user = resource.user self?.isLoading = false if self?.canEditAnyInfo ?? false { self?.navigationItem.rightBarButtonItem = self?.editButton } self?.tableView.reloadData() } case .error: Alert(key: "alert.load_profile_error").present(handler: { _ in self?.navigationController?.popViewController(animated: true) }) } } } func bindUserData() { avatarView.username = user?.username name.text = user?.name username.text = user?.username email.text = user?.emails.first?.email updateUserStatus() } func updateUserStatus() { statusValueLabel.text = viewModel.userStatus } // MARK: State Management var isEditingProfile = false { didSet { applyTheme() } } @objc func beginEditing() { isEditingProfile = true navigationItem.title = viewModel.editingTitle navigationItem.rightBarButtonItem = saveButton navigationItem.hidesBackButton = true navigationItem.leftBarButtonItem = cancelButton if authSettings?.isAllowedToEditAvatar ?? false { avatarButton.setImage(editingAvatarImage, for: .normal) avatarButton.accessibilityLabel = avatarEditingButtonAccessibilityLabel } enableUserInteraction() } @objc func endEditing() { isEditingProfile = false bindUserData() navigationItem.title = viewModel.title navigationItem.hidesBackButton = false navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = editButton if authSettings?.isAllowedToEditAvatar ?? false { avatarButton.setImage(nil, for: .normal) avatarButton.accessibilityLabel = avatarButtonAccessibilityLabel } disableUserInteraction() } func enableUserInteraction() { avatarButton.isEnabled = authSettings?.isAllowedToEditAvatar ?? false if authSettings?.isAllowedToEditName ?? false { name.isEnabled = true } else { name.isEnabled = false } if authSettings?.isAllowedToEditUsername ?? false { username.isEnabled = true } else { username.isEnabled = false } if authSettings?.isAllowedToEditEmail ?? false { email.isEnabled = true } else { email.isEnabled = false } if authSettings?.isAllowedToEditName ?? false { name.becomeFirstResponder() } else if authSettings?.isAllowedToEditUsername ?? false { username.becomeFirstResponder() } else if authSettings?.isAllowedToEditEmail ?? false { email.becomeFirstResponder() } } func disableUserInteraction() { hideKeyboard() avatarButton.isEnabled = false name.isEnabled = false username.isEnabled = false email.isEnabled = false } // MARK: Accessibility var avatarButtonAccessibilityLabel: String? = VOLocalizedString("preferences.profile.edit.label") var avatarEditingButtonAccessibilityLabel: String? = VOLocalizedString("preferences.profile.editing.label") // MARK: Actions @IBAction func saveProfile(_ sender: UIBarButtonItem) { hideKeyboard() guard let name = name.text, let username = username.text, let email = email.text, !name.isEmpty, !username.isEmpty, !email.isEmpty else { Alert(key: "alert.update_profile_empty_fields").present() return } guard email.isValidEmail else { Alert(key: "alert.update_profile_invalid_email").present() return } var userRaw = JSON([:]) if name != self.user?.name { userRaw["name"].string = name } if username != self.user?.username { userRaw["username"].string = username } if email != self.user?.emails.first?.email { userRaw["emails"] = [["address": email]] } let shouldUpdateUser = name != self.user?.name || username != self.user?.username || email != self.user?.emails.first?.email if !shouldUpdateUser { update(user: nil) return } let user = User() user.map(userRaw, realm: nil) if !(self.user?.emails.first?.email == email) { requestPasswordToUpdate(user: user) } else { update(user: user) } } fileprivate func requestPasswordToUpdate(user: User) { let alert = UIAlertController( title: localized("myaccount.settings.profile.password_required.title"), message: localized("myaccount.settings.profile.password_required.message"), preferredStyle: .alert ) let updateUserAction = UIAlertAction(title: localized("myaccount.settings.profile.actions.save"), style: .default, handler: { _ in self.currentPassword = alert.textFields?.first?.text self.update(user: user) }) updateUserAction.isEnabled = false alert.addTextField(configurationHandler: { textField in textField.placeholder = localized("myaccount.settings.profile.password_required.placeholder") textField.textContentType = .password textField.isSecureTextEntry = true _ = NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main) { _ in updateUserAction.isEnabled = !(textField.text?.isEmpty ?? false) } }) alert.addAction(UIAlertAction(title: localized("global.cancel"), style: .cancel, handler: nil)) alert.addAction(updateUserAction) present(alert, animated: true) } /** This method will only update the avatar image of the user. */ fileprivate func updateAvatar() { guard let avatarFile = avatarFile else { return } startLoading() isUploadingAvatar = true let client = API.current()?.client(UploadClient.self) client?.uploadAvatar(data: avatarFile.data, filename: avatarFile.name, mimetype: avatarFile.type, completion: { [weak self] _ in guard let self = self else { return } if !self.isUpdatingUser { self.alertSuccess(title: localized("alert.update_profile_success.title")) } self.isUploadingAvatar = false self.avatarView.avatarPlaceholder = UIImage(data: avatarFile.data) self.avatarView.refreshCurrentAvatar(withCachedData: avatarFile.data, completion: { self.stopLoading() }) self.avatarFile = nil }) } /** This method will only update the user information. */ fileprivate func updateUserInformation(user: User) { isUpdatingUser = true if !isUploadingAvatar { startLoading() } let stopLoading: (_ shouldEndEditing: Bool) -> Void = { [weak self] shouldEndEditing in self?.isUpdatingUser = false self?.stopLoading(shouldEndEditing: shouldEndEditing) } let updateUserRequest = UpdateUserRequest(user: user, currentPassword: currentPassword) api?.fetch(updateUserRequest) { [weak self] response in guard let self = self else { return } switch response { case .resource(let resource): if let errorMessage = resource.errorMessage { stopLoading(false) Alert(key: "alert.update_profile_error").withMessage(errorMessage).present() return } self.user = resource.user stopLoading(true) if !self.isUploadingAvatar { self.alertSuccess(title: localized("alert.update_profile_success.title")) } case .error: stopLoading(false) Alert(key: "alert.update_profile_error").present() } } } /** This method will check if there's an new avatar to be updated and if there's any information on the user to be updated as well. They're both different API calls that need to be made. */ fileprivate func update(user: User?) { if avatarFile != nil { updateAvatar() } guard let user = user else { if !isUploadingAvatar { endEditing() } return } updateUserInformation(user: user) } @IBAction func didPressAvatarButton(_ sender: UIButton) { hideKeyboard() let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if UIImagePickerController.isSourceTypeAvailable(.camera) { alert.addAction(UIAlertAction(title: localized("chat.upload.take_photo"), style: .default, handler: { (_) in self.openCamera() })) } alert.addAction(UIAlertAction(title: localized("chat.upload.choose_from_library"), style: .default, handler: { (_) in self.openPhotosLibrary() })) alert.addAction(UIAlertAction(title: localized("global.cancel"), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } @objc func didPressCancelEditingButton() { avatarView.avatarPlaceholder = nil avatarView.imageView.image = nil endEditing() } @objc func hideKeyboard() { view.endEditing(true) } func startLoading() { view.isUserInteractionEnabled = false navigationItem.leftBarButtonItem?.isEnabled = false navigationItem.rightBarButtonItem = UIBarButtonItem(customView: activityIndicator) } func stopLoading(shouldEndEditing: Bool = true, shouldRefreshAvatar: Bool = false) { if !isUpdatingUser, !isUploadingAvatar { view.isUserInteractionEnabled = true navigationItem.leftBarButtonItem?.isEnabled = true if shouldEndEditing { endEditing() } else { navigationItem.rightBarButtonItem = saveButton } } } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let newPassword = segue.destination as? NewPasswordTableViewController { newPassword.passwordUpdated = { [weak self] newPasswordViewController in newPasswordViewController?.navigationController?.popViewControler(animated: true, completion: { self?.alertSuccess(title: localized("alert.update_password_success.title")) }) } } } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return numberOfSections } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 1: return viewModel.profileSectionTitle default: return "" } } } extension EditProfileTableViewController: UINavigationControllerDelegate {} extension EditProfileTableViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { let filename = String.random() var file: FileUpload? if let image = info[.editedImage] as? UIImage { file = UploadHelper.file( for: image.compressedForUpload, name: "\(filename.components(separatedBy: ".").first ?? "image").jpeg", mimeType: "image/jpeg" ) avatarView.imageView.image = image } avatarFile = file dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } extension EditProfileTableViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case name: username.becomeFirstResponder() case username: email.becomeFirstResponder() case email: hideKeyboard() default: break } return true } } extension EditProfileTableViewController { override func applyTheme() { super.applyTheme() guard let theme = view.theme else { return } switch isEditingProfile { case false: name.textColor = theme.titleText username.textColor = theme.titleText email.textColor = theme.titleText case true: name.textColor = (authSettings?.isAllowedToEditName ?? false) ? theme.titleText : theme.auxiliaryText username.textColor = (authSettings?.isAllowedToEditName ?? false) ? theme.titleText : theme.auxiliaryText email.textColor = (authSettings?.isAllowedToEditName ?? false) ? theme.titleText : theme.auxiliaryText } } }
e68fcd4b1d882066c8c1262c66d155b2
31.458404
156
0.624124
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/Bookmarks/BookmarksTabViewController.swift
apache-2.0
4
@objc(MWMBookmarksTabViewController) final class BookmarksTabViewController: TabViewController { @objc enum ActiveTab: Int { case user = 0 case catalog } private static let selectedIndexKey = "BookmarksTabViewController_selectedIndexKey" @objc public var activeTab: ActiveTab = ActiveTab(rawValue: UserDefaults.standard.integer(forKey: BookmarksTabViewController.selectedIndexKey)) ?? .user { didSet { UserDefaults.standard.set(activeTab.rawValue, forKey: BookmarksTabViewController.selectedIndexKey) } } private weak var coordinator: BookmarksCoordinator? @objc init(coordinator: BookmarksCoordinator?) { super.init(nibName: nil, bundle: nil) self.coordinator = coordinator } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let bookmarks = BMCViewController(coordinator: coordinator) let catalog = DownloadedBookmarksViewController(coordinator: coordinator) bookmarks.title = L("bookmarks") catalog.title = L("guides") viewControllers = [bookmarks, catalog] title = L("bookmarks_guides"); tabView.selectedIndex = activeTab.rawValue tabView.delegate = self } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) activeTab = ActiveTab(rawValue: tabView.selectedIndex ?? 0) ?? .user } } extension BookmarksTabViewController: TabViewDelegate { func tabView(_ tabView: TabView, didSelectTabAt index: Int) { let selectedTab = index == 0 ? "my" : "downloaded" Statistics.logEvent("Bookmarks_Tab_click", withParameters: [kStatValue : selectedTab]) } }
46dbbc7af9a725a49cb288e7ad65a3b5
31.018868
104
0.735415
false
false
false
false
nkirby/Humber
refs/heads/master
Humber/_src/Theming/ThemeElements.swift
mit
1
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit internal enum ColorType { case PrimaryTextColor case SecondaryTextColor case DisabledTextColor case TintColor case ViewBackgroundColor case CellBackgroundColor case DividerColor } internal enum FontType { case Bold(CGFloat) case Regular(CGFloat) case Italic(CGFloat) } internal protocol Themable { var name: String { get } func color(type type: ColorType) -> UIColor func font(type type: FontType) -> UIFont }
9009b41d5e8579cd94856f57fcac34bb
20.758621
58
0.575277
false
false
false
false
justin999/gitap
refs/heads/master
gitap/GitHubAPIError.swift
mit
1
struct GitHubAPIError : JSONDecodable, Error { struct FieldError : JSONDecodable { let resource: String let field: String let code: String init(json: Any) throws { guard let dictionary = json as? [String : Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let resource = dictionary["resource"] as? String else { throw JSONDecodeError.missingValue(key: "resource", actualValue: dictionary["resource"]) } guard let field = dictionary["field"] as? String else { throw JSONDecodeError.missingValue(key: "field", actualValue: dictionary["field"]) } guard let code = dictionary["code"] as? String else { throw JSONDecodeError.missingValue(key: "code", actualValue: dictionary["code"]) } self.resource = resource self.field = field self.code = code } } let message: String let fieldErrors: [FieldError] init(json: Any) throws { guard let dictionary = json as? [String : Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let message = dictionary["message"] as? String else { throw JSONDecodeError.missingValue(key: "message", actualValue: dictionary["message"]) } let fieldErrorObjects = dictionary["errors"] as? [Any] ?? [] let fieldErrors = try fieldErrorObjects.map { return try FieldError(json: $0) } self.message = message self.fieldErrors = fieldErrors } }
9023596e8cc11d9a9ea4be3e9feeb0dc
33.74
104
0.560161
false
false
false
false
sameertotey/LimoService
refs/heads/master
LimoService/PreviousLocationLookupViewController.swift
mit
1
// // PreviousLocationLookupViewController.swift // LimoService // // Created by Sameer Totey on 4/1/15. // Copyright (c) 2015 Sameer Totey. All rights reserved. // import UIKit class PreviousLocationLookupViewController: PFQueryTableViewController { weak var currentUser: PFUser! var selectedLocation: LimoUserLocation? override init(style: UITableViewStyle, className: String!) { super.init(style: style, className: className) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.parseClassName = "LimoUserLocation" // self.textKey = "address" self.pullToRefreshEnabled = true self.objectsPerPage = 20 } private func alert(message : String) { let alert = UIAlertController(title: "Oops something went wrong.", message: message, preferredStyle: UIAlertControllerStyle.Alert) let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) let settings = UIAlertAction(title: "Settings", style: UIAlertActionStyle.Default) { (action) -> Void in UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) return } alert.addAction(settings) alert.addAction(action) self.presentViewController(alert, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 60 self.tableView.rowHeight = UITableViewAutomaticDimension } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func queryForTable() -> PFQuery { if let query = LimoUserLocation.query() { query.whereKey("owner", equalTo: currentUser) // expect currentUser to be set here query.orderByDescending("createdAt") query.limit = 200; return query } else { let query = PFQuery(className: "LimoUserLocation") query.whereKey("owner", equalTo: currentUser) // expect currentUser to be set here query.orderByDescending("createdAt") query.limit = 200; return query } } override func objectAtIndexPath(indexPath: NSIndexPath!) -> PFObject? { var obj : PFObject? = nil if let allObjects = self.objects { if indexPath.row < allObjects.count { obj = allObjects[indexPath.row] as? PFObject } } return obj } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject!) -> PFTableViewCell? { let cell = tableView.dequeueReusableCellWithIdentifier("LocationCell", forIndexPath: indexPath) as! LocationLookupTableViewCell cell.nameLabel.text = object.valueForKey("name") as? String cell.addressLabel.text = object.valueForKey("address") as? String return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "return the Location"){ } } // MARK: - TableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let selectedObject = objectAtIndexPath(indexPath) { if selectedObject is LimoUserLocation { selectedLocation = (selectedObject as! LimoUserLocation) performSegueWithIdentifier("Return Selection", sender: nil) } else { println("The type of the object \(selectedObject) is not LimoUserLocation it is ..") } } } }
512b4175a61f38ce259df5aa20000f99
35.775701
138
0.640152
false
false
false
false
tkareine/MiniFuture
refs/heads/master
Source/Try.swift
mit
1
import Foundation public enum Try<T> { case success(T) case failure(Error) public func flatMap<U>(_ f: (T) throws -> Try<U>) -> Try<U> { switch self { case .success(let value): do { return try f(value) } catch { return .failure(error) } case .failure(let error): return .failure(error) } } public func map<U>(_ f: (T) throws -> U) -> Try<U> { return flatMap { e in do { return .success(try f(e)) } catch { return .failure(error) } } } public func value() throws -> T { switch self { case .success(let value): return value case .failure(let error): throw error } } public var isSuccess: Bool { switch self { case .success: return true case .failure: return false } } public var isFailure: Bool { return !isSuccess } } extension Try: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { switch self { case .success(let value): return "Try.success(\(value))" case .failure(let error): return "Try.failure(\(error))" } } public var debugDescription: String { switch self { case .success(let value): return "Try.success(\(String(reflecting: value)))" case .failure(let error): return "Try.failure(\(String(reflecting: error)))" } } } /** * Try enumeration does not adopt Equatable protocol, because that would limit * the allowed values of generic type T. Instead, we provide `==` operator. */ public func ==<T: Equatable>(lhs: Try<T>, rhs: Try<T>) -> Bool { switch (lhs, rhs) { case (.success(let lhs), .success(let rhs)): return lhs == rhs case (.failure(let lhs as NSError), .failure(let rhs as NSError)): return lhs.domain == rhs.domain && lhs.code == rhs.code default: return false } } public func !=<T: Equatable>(lhs: Try<T>, rhs: Try<T>) -> Bool { return !(lhs == rhs) }
01407a90edfe2e25c132d0cc1fd42fed
20.989011
78
0.591204
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Live/Model/CGSSBeatmapNote.swift
mit
2
// // CGSSBeatmapNote.swift // DereGuide // // Created by zzk on 21/10/2017. // Copyright © 2017 zzk. All rights reserved. // import Foundation import UIKit class CGSSBeatmapNote { // 判定范围类型(用于计算得分, 并非按键类型) enum RangeType: Int { case click case flick case slide static let hold = RangeType.click } // note 类型 enum Style { enum FlickDirection { case left case right } case click case flick(FlickDirection) case slide case hold case wideClick case wideFlick(FlickDirection) case wideSlide var isWide: Bool { switch self { case .click, .flick, .hold, .slide: return false default: return true } } } var width: Int { switch style { case .click, .flick, .hold, .slide: return 1 default: return status } } var id: Int! var sec: Float! var type: Int! var startPos: Int! var finishPos: Int! var status: Int! var sync: Int! var groupId: Int! // 0 no press, 1 start, 2 end var longPressType = 0 // used in shifting bpm var offset: Float = 0 // from 1 to max combo var comboIndex: Int = 1 // context free note information, so each long press slide and filck note need to know the related note weak var previous: CGSSBeatmapNote? weak var next: CGSSBeatmapNote? weak var along: CGSSBeatmapNote? } extension CGSSBeatmapNote { func append(_ anotherNote: CGSSBeatmapNote) { self.next = anotherNote anotherNote.previous = self } func intervalTo(_ anotherNote: CGSSBeatmapNote) -> Float { return anotherNote.sec - sec } var offsetSecond: Float { return sec + offset } } extension CGSSBeatmapNote { var rangeType: RangeType { switch (status, type) { case (1, _), (2, _): return .flick case (_, 3): return .slide case (_, 2): return .hold default: return .click } } var style: Style { switch (status, type) { case (1, 1): return .flick(.left) case (2, 1): return .flick(.right) case (_, 2): return .hold case (_, 3): return .slide case (_, 4): return .wideClick case (_, 5): return .wideSlide case (_, 6): return .wideFlick(.left) case (_, 7): return .wideFlick(.right) default: return .click } } }
73c3ac209eac914113e4c8a4522fb161
20.412214
107
0.504456
false
false
false
false
jegumhon/URWeatherView
refs/heads/master
URWeatherView/SpriteAssets/URRainGroundEmitterNode.swift
mit
1
// // URRainGroundEmitterNode.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 15.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit open class URRainGroundEmitterNode: SKEmitterNode { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init() { super.init() let bundle = Bundle(for: URRainGroundEmitterNode.self) let particleImage = UIImage(named: "spark", in: bundle, compatibleWith: nil)! self.particleTexture = SKTexture(image: particleImage) self.particleBirthRate = 100.0 // self.particleBirthRateMax? self.particleLifetime = 0.1 self.particleLifetimeRange = 0.0 self.particlePositionRange = CGVector(dx: 363.44, dy: 0.0) self.zPosition = 0.0 self.emissionAngle = CGFloat(269.863 * .pi / 180.0) self.emissionAngleRange = CGFloat(22.918 * .pi / 180.0) self.particleSpeed = 5.0 self.particleSpeedRange = 5.0 self.xAcceleration = 0.0 self.yAcceleration = 0.0 self.particleAlpha = 0.8 self.particleAlphaRange = 0.2 self.particleAlphaSpeed = 0.0 self.particleScale = 0.0 self.particleScaleRange = 0.15 self.particleScaleSpeed = 0.0 self.particleRotation = 0.0 self.particleRotationRange = 0.0 self.particleRotationSpeed = 0.0 self.particleColorBlendFactor = 1.0 self.particleColorBlendFactorRange = 0.0 self.particleColorBlendFactorSpeed = 0.0 self.particleColorSequence = SKKeyframeSequence(keyframeValues: [UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0), UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0)], times: [0.0, 1.0]) self.particleBlendMode = .alpha } }
b123c49723b4106fb104b6ad956e32a2
36.897959
232
0.650512
false
false
false
false
iSame7/Glassy
refs/heads/master
Glassy/Glassy/GlassyScrollView.swift
mit
1
// // GlassyScrollView.swift // Glassy // // Created by Sameh Mabrouk on 6/27/15. // Copyright (c) 2015 smapps. All rights reserved. // import UIKit //Default Blur Settings. let blurRadious:CGFloat = 14.0 let blurTintColor:UIColor = UIColor(white: 0, alpha: 0.3) let blurDeltaFactor:CGFloat = 1.4 //How much the background move when scrolling. let maxBackgroundMovementVerticle:CGFloat = 30 let maxBackgroundMovementHorizontal:CGFloat = 150 //the value of the fading space on the top between the view and navigation bar let topFadingHeightHalf:CGFloat = 10 @objc protocol GlassyScrollViewDelegate:NSObjectProtocol{ optional func floraView(floraView: AnyObject, numberOfRowsInSection section: Int) -> Int //use this to configure your foregroundView when the frame of the whole view changed optional func glassyScrollView(glassyScrollView: GlassyScrollView, didChangedToFrame fram: CGRect) //make custom blur without messing with default settings optional func glassyScrollView(glassyScrollView: GlassyScrollView, blurForImage image: UIImage) -> UIImage } class GlassyScrollView: UIView, UIScrollViewDelegate { private var backgroundImage: UIImage! //Default blurred is provided. private var blurredBackgroundImage: UIImage! //The view that will contain all the info private var foregroundView: UIView! //Shadow layers. private var topShadowLayer:CALayer! private var botShadowLayer:CALayer! //Masking private var foregroundContainerView:UIView! private var topMaskImageView:UIImageView! private var backgroundScrollView:UIScrollView! var foregroundScrollView:UIScrollView! //How much view is showed up from the bottom. var viewDistanceFromBottom:CGFloat! //set this only when using navigation bar of sorts. let topLayoutGuideLength:CGFloat = 0.0 var constraitView:UIView! var backgroundImageView:UIImageView! var blurredBackgroundImageView:UIImageView! //delegate. var delegate:GlassyScrollViewDelegate! // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, backgroundImage:UIImage, blurredImage:UIImage?, viewDistanceFromBottom:CGFloat, foregroundView:UIView) { super.init(frame: frame) self.backgroundImage = backgroundImage if blurredImage != NSNull(){ // self.blurredBackgroundImage = blurredImage self.blurredBackgroundImage = backgroundImage.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } else{ //Check if delegate conform to protocol or not. if self.delegate.respondsToSelector(Selector("glassyScrollView:blurForImage:")){ self.blurredBackgroundImage = self.delegate.glassyScrollView!(self, blurForImage: self.backgroundImage) } else{ //implement live blurring effect. self.blurredBackgroundImage = backgroundImage.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } } self.viewDistanceFromBottom = viewDistanceFromBottom self.foregroundView = foregroundView //Autoresize self.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth //Create Views self.createBackgroundView() self.createForegroundView() // self.createTopShadow() self.createBottomShadow() } func initWithFrame(){ } // MARK: - Public Methods func scrollHorizontalRatio(ratio:CGFloat){ // when the view scroll horizontally, this works the parallax magic backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal+ratio*maxBackgroundMovementHorizontal, backgroundScrollView.contentOffset.y) } func scrollVerticallyToOffset(offsetY:CGFloat){ foregroundScrollView.contentOffset=CGPointMake(foregroundScrollView.contentOffset.x, offsetY) } // MARK: - Setters func setViewFrame(frame:CGRect){ super.frame = frame //work background let bounds:CGRect = CGRectOffset(frame, -frame.origin.x, -frame.origin.y) backgroundScrollView.frame=bounds backgroundScrollView.contentSize = CGSizeMake(bounds.size.width + 2*maxBackgroundMovementHorizontal, self.bounds.size.height+maxBackgroundMovementVerticle) backgroundScrollView.contentOffset=CGPointMake(maxBackgroundMovementHorizontal, 0) constraitView.frame = CGRectMake(0, 0, bounds.size.width + 2*maxBackgroundMovementHorizontal, bounds.size.height+maxBackgroundMovementVerticle) //foreground foregroundContainerView.frame = bounds foregroundScrollView.frame=bounds foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) foregroundScrollView.contentSize=CGSizeMake(bounds.size.width, foregroundView.frame.origin.y + foregroundView.bounds.size.height) //Shadows // topShadowLayer.frame=CGRectMake(0, 0, bounds.size.width, foregroundScrollView.contentInset.top + topFadingHeightHalf) botShadowLayer.frame=CGRectMake(0, bounds.size.height - viewDistanceFromBottom, bounds.size.width, bounds.size.height) // if self.delegate.respondsToSelector(Selector("glassyScrollView:didChangedToFrame:")){ // delegate.glassyScrollView!(self, didChangedToFrame: frame) // } } func setTopLayoutGuideLength(topLayoutGuideLength:CGFloat){ if topLayoutGuideLength==0 { return } //set inset foregroundScrollView.contentInset = UIEdgeInsetsMake(topLayoutGuideLength, 0, 0, 0) //reposition foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) //resize contentSize foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) //reset the offset if foregroundScrollView.contentOffset.y == 0{ foregroundScrollView.contentOffset = CGPointMake(0, -foregroundScrollView.contentInset.top) } //adding new mask foregroundContainerView.layer.mask = createTopMaskWithSize(CGSizeMake(foregroundContainerView.frame.size.width, foregroundContainerView.frame.size.height), startFadAtTop: foregroundScrollView.contentInset.top - topFadingHeightHalf, endAtBottom: foregroundScrollView.contentInset.top + topFadingHeightHalf, topColor: UIColor(white: 1.0, alpha: 0.0), botColor: UIColor(white: 1.0, alpha: 1.0)) //recreate shadow createTopShadow() } func setViewDistanceFromBottom(vDistanceFromBottom:CGFloat){ viewDistanceFromBottom = vDistanceFromBottom foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.bounds.size.width)/2, foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) //shadows botShadowLayer.frame = CGRectOffset(botShadowLayer.bounds, 0, self.frame.size.height - viewDistanceFromBottom) } func setBackgroundImage(backgroundImg:UIImage, overWriteBlur:Bool, animated:Bool, interval:NSTimeInterval){ backgroundImage = backgroundImg if overWriteBlur{ blurredBackgroundImage = backgroundImg.applyBlurWithRadius(blurRadious, tintColor: blurTintColor, saturationDeltaFactor: blurDeltaFactor, maskImage: nil) } if animated{ let previousBackgroundImageView:UIImageView = backgroundImageView let previousBlurredBackgroundImageView:UIImageView = blurredBackgroundImageView createBackgroundImageView() backgroundImageView.alpha = 0 blurredBackgroundImageView.alpha=0 // blur needs to get animated first if the background is blurred if previousBlurredBackgroundImageView.alpha == 1{ UIView.animateWithDuration(interval, animations: { () -> Void in self.blurredBackgroundImageView.alpha=previousBlurredBackgroundImageView.alpha }, completion: { (Bool) -> Void in self.backgroundImageView.alpha=previousBackgroundImageView.alpha previousBackgroundImageView.removeFromSuperview() previousBlurredBackgroundImageView.removeFromSuperview() }) } else{ UIView.animateWithDuration(interval, animations: { () -> Void in self.backgroundImageView.alpha=self.backgroundImageView.alpha self.blurredBackgroundImageView.alpha=previousBlurredBackgroundImageView.alpha }, completion: { (Bool) -> Void in previousBackgroundImageView.removeFromSuperview() previousBlurredBackgroundImageView.removeFromSuperview() }) } } else{ backgroundImageView.image=backgroundImage blurredBackgroundImageView.image=blurredBackgroundImage } } func blurBackground(shouldBlur:Bool){ if shouldBlur{ blurredBackgroundImageView.alpha = 1 } else{ blurredBackgroundImageView.alpha = 0 } } // MARK: - Views creation // MARK: - ScrollViews func createBackgroundView(){ self.backgroundScrollView = UIScrollView(frame: self.frame) self.backgroundScrollView.userInteractionEnabled=true self.backgroundScrollView.contentSize = CGSize(width: self.frame.size.width + (2*maxBackgroundMovementHorizontal), height: self.frame.size.height+maxBackgroundMovementVerticle) self.backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal, 0) self.addSubview(self.backgroundScrollView) self.constraitView = UIView(frame: CGRectMake(0, 0, self.frame.size.width + (2*maxBackgroundMovementHorizontal), self.frame.size.height+maxBackgroundMovementVerticle)) self.backgroundScrollView.addSubview(self.constraitView) self.createBackgroundImageView() } func createBackgroundImageView(){ self.backgroundImageView = UIImageView(image: self.backgroundImage) self.backgroundImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.backgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill self.constraitView.addSubview(self.backgroundImageView) self.blurredBackgroundImageView = UIImageView(image: self.blurredBackgroundImage) self.blurredBackgroundImageView.setTranslatesAutoresizingMaskIntoConstraints(false) self.blurredBackgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill self.blurredBackgroundImageView.alpha=0 self.constraitView.addSubview(self.blurredBackgroundImageView) var viewBindingsDict: NSMutableDictionary = NSMutableDictionary() viewBindingsDict.setValue(backgroundImageView, forKey: "backgroundImageView") self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundImageView]|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject])) self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundImageView]|", options: nil, metrics: nil, views: viewBindingsDict as [NSObject : AnyObject])) var blurredViewBindingsDict: NSMutableDictionary = NSMutableDictionary() blurredViewBindingsDict.setValue(blurredBackgroundImageView, forKey: "blurredBackgroundImageView") self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[blurredBackgroundImageView]|", options: nil, metrics: nil, views: blurredViewBindingsDict as [NSObject : AnyObject])) self.constraitView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[blurredBackgroundImageView]|", options: nil, metrics: nil, views: blurredViewBindingsDict as [NSObject : AnyObject])) } func createForegroundView(){ self.foregroundContainerView = UIView(frame: self.frame) self.addSubview(self.foregroundContainerView) self.foregroundScrollView=UIScrollView(frame: self.frame) self.foregroundScrollView.delegate=self self.foregroundScrollView.showsVerticalScrollIndicator=false self.foregroundScrollView.showsHorizontalScrollIndicator=false self.foregroundContainerView.addSubview(self.foregroundScrollView) let tapRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("foregroundTapped:")) foregroundScrollView.addGestureRecognizer(tapRecognizer) foregroundView.frame = CGRectOffset(foregroundView.bounds, (foregroundScrollView.frame.size.width - foregroundView.frame.size.width)/2, foregroundScrollView.frame.size.height - viewDistanceFromBottom) foregroundScrollView.addSubview(foregroundView) foregroundScrollView.contentSize = CGSizeMake(self.frame.size.width, foregroundView.frame.origin.y + foregroundView.frame.size.height) } // MARK: - Shadow and mask layer func createTopMaskWithSize(size:CGSize, startFadAtTop:CGFloat, endAtBottom:CGFloat, topColor:UIColor, botColor:UIColor) -> CALayer{ let top = startFadAtTop / size.height let bottom = endAtBottom / size.height let maskLayer:CAGradientLayer = CAGradientLayer() maskLayer.anchorPoint = CGPointZero maskLayer.startPoint = CGPointMake(0.5, 0.0) maskLayer.endPoint = CGPointMake(0.5, 1.0) maskLayer.colors = NSArray(arrayLiteral: topColor.CGColor, topColor.CGColor, botColor.CGColor, botColor.CGColor) as [AnyObject] maskLayer.locations = NSArray(arrayLiteral: 0.0, top, bottom, 1.0) as [AnyObject] maskLayer.frame = CGRectMake(0, 0, size.width, size.height) return maskLayer } func createTopShadow(){ topShadowLayer = self.createTopMaskWithSize(CGSizeMake(foregroundContainerView.frame.size.width, foregroundScrollView.contentInset.top + topFadingHeightHalf), startFadAtTop:foregroundScrollView.contentInset.top + topFadingHeightHalf , endAtBottom: foregroundScrollView.contentInset.top + topFadingHeightHalf, topColor: UIColor(white: 0, alpha: 0.15), botColor: UIColor(white: 0, alpha: 0)) self.layer.insertSublayer(topShadowLayer, below: foregroundContainerView.layer) } func createBottomShadow(){ botShadowLayer = self.createTopMaskWithSize(CGSizeMake(self.frame.size.width, viewDistanceFromBottom), startFadAtTop:0 , endAtBottom: viewDistanceFromBottom, topColor: UIColor(white: 0, alpha: 0), botColor: UIColor(white: 0, alpha: 0.8)) self.layer.insertSublayer(botShadowLayer, below: foregroundContainerView.layer) } // MARK: - foregroundScrollView Tap Action func foregroundTapped(tapRecognizer:UITapGestureRecognizer){ let tappedPoint:CGPoint = tapRecognizer.locationInView(foregroundScrollView) if tappedPoint.y < foregroundScrollView.frame.size.height{ var ratio:CGFloat! if foregroundScrollView.contentOffset.y == foregroundScrollView.contentInset.top{ ratio=1 } else{ ratio=0 } foregroundScrollView.setContentOffset(CGPointMake(0, ratio * foregroundView.frame.origin.y - foregroundScrollView.contentInset.top), animated: true) } } // MARK: - Delegate // MARK: - UIScrollView func scrollViewDidScroll(scrollView: UIScrollView) { //translate into ratio to height var ratio:CGFloat = (scrollView.contentOffset.y + foregroundScrollView.contentInset.top)/(foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) if ratio < 0{ ratio = 0 } if ratio > 1{ ratio=1 } //set background scroll backgroundScrollView.contentOffset = CGPointMake(maxBackgroundMovementHorizontal, ratio * maxBackgroundMovementVerticle) //set alpha blurredBackgroundImageView.alpha = ratio } func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { var ratio = (targetContentOffset.memory.y + foregroundScrollView.contentInset.top) / (foregroundScrollView.frame.size.height - foregroundScrollView.contentInset.top - viewDistanceFromBottom) if ratio > 0 && ratio < 1{ if velocity.y == 0{ if ratio>0.5{ratio=1} else{ratio=0} } else if velocity.y > 0 { if ratio>0.1{ratio=1} else{ratio=0} } else { if ratio>0.9{ratio=1} else{ratio=0} } targetContentOffset.memory.y=ratio * foregroundView.frame.origin.y - foregroundScrollView.contentInset.top } } }
77b70b9fa2e533d753da4ef8f2a09955
40.196796
399
0.716992
false
false
false
false
LonelyRun/VAKit
refs/heads/master
Demo/VAKit/ViewController.swift
mit
1
// // ViewController.swift // VAKit // // Created by admin on 2017/4/21. // Copyright © 2017年 admin. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label = VAImageLabelView(imageName: "https://img6.bdstatic.com/img/image/smallpic/h2.jpg", title: "4就开了", type: .DefaultType) label.layer.borderWidth = 1 label.layer.borderColor = UIColor.black.cgColor label.spacingLength = 10 label.leftTopMargin = 0 label.rightBottomMargin = -10 view.addSubview(label) label.snp.makeConstraints { (make) in make.top.equalTo(60) make.centerX.equalTo(view) } label.label.text = "123" } }
c7f8abca73f4fb6b90c130355e081d21
24.548387
137
0.623737
false
false
false
false
netsells/NSUtils
refs/heads/master
NSUtils/Classes/Views/ProgressBarView.swift
mit
1
// // ProgressBarView.swift // NSUtils // // Created by Jack Colley on 01/02/2018. // Copyright © 2018 Netsells. All rights reserved. // import Foundation import UIKit open class ProgressBarView: UIView { @IBInspectable public var startColour: UIColor = UIColor.white @IBInspectable public var endColour: UIColor = UIColor.blue @IBInspectable public var completionPercentage: CGFloat = 0.0 // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override open func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let colours: [CGColor] = [startColour.cgColor, endColour.cgColor] // Should almost always be RGB - We don't really want to use CMYK let colourSpace = CGColorSpaceCreateDeviceRGB() let colourLocations: [CGFloat] = [0.0, 1.0] let gradient = CGGradient(colorsSpace: colourSpace, colors: colours as CFArray, locations: colourLocations) let startPoint = CGPoint(x: 0, y: self.frame.height) let endPoint = CGPoint(x: self.frame.width * completionPercentage, y: self.frame.height) context!.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0)) } }
335dd32532ade029c25217e0335a551b
35.611111
128
0.711684
false
false
false
false
kevintulod/CascadeKit-iOS
refs/heads/master
CascadeKit/CascadeKit/Cascade Controller/CascadeController.swift
mit
1
// // CascadeController.swift // CascadeKit // // Created by Kevin Tulod on 1/7/17. // Copyright © 2017 Kevin Tulod. All rights reserved. // import UIKit public class CascadeController: UIViewController { @IBOutlet weak var leftViewContainer: UIView! @IBOutlet weak var rightViewContainer: UIView! @IBOutlet weak var dividerView: CascadeDividerView! @IBOutlet weak var dividerViewWidthConstraint: NSLayoutConstraint! @IBOutlet weak var dividerViewPositionConstraint: NSLayoutConstraint! internal var controllers = [UINavigationController]() internal weak var leftController: UINavigationController? { didSet { guard let leftController = leftController else { return } addChildViewController(leftController) leftViewContainer.fill(with: leftController.view) leftController.rootViewController?.navigationItem.leftBarButtonItem = nil } } internal weak var rightController: UINavigationController? { didSet { guard let rightController = rightController else { return } addChildViewController(rightController) rightViewContainer.fill(with: rightController.view) if controllers.count > 0 { rightController.rootViewController?.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Close", style: .plain, target: self, action: #selector(CascadeController.popLastViewController)) } } } /// Minimum size for left and right views public var minimumViewSize = CGFloat(250) /// Duration of cascade animations in seconds public var animationDuration = TimeInterval(0.25) // MARK: - Creation private static let storyboardName = "Cascade" private static let storyboardIdentifier = "CascadeController" public static func create() -> CascadeController { let storyboard = UIStoryboard(name: storyboardName, bundle: Bundle(for: CascadeController.self)) guard let controller = storyboard.instantiateViewController(withIdentifier: storyboardIdentifier) as? CascadeController else { fatalError("`Cascade` storyboard is missing required reference to `CascadeController`") } let _ = controller.view return controller } public override func viewDidLoad() { super.viewDidLoad() dividerView.delegate = self setupStyling() } public override func addChildViewController(_ childController: UIViewController) { super.addChildViewController(childController) } /// Sets up the cascade controller with the initial view controllers public func setup(first: UINavigationController, second: UINavigationController) { leftController = first rightController = second } /// Cascades the view controller to the top of the stack public func cascade(viewController cascadeController: UINavigationController, sender: UINavigationController? = nil) { if sender === leftController { // If the provided sender is the second-to-last in the stack, replace the last controller popLastController() addControllerToStack(cascadeController) rightController = cascadeController } else { // All other cases, push the controller to the end animate(withForwardCascadeController: cascadeController, preAnimation: { Void in self.addControllerToStack(self.leftController) self.leftController = self.rightController }, postAnimation: { Void in self.rightController = cascadeController }, completion: nil) } } /// Pops the last controller off the top of the stack public func popLastViewController() { guard let poppedController = popLastController() else { NSLog("No controller in stack to pop.") return } let newRightController = self.leftController let dismissingController = self.rightController animate(withBackwardCascadeController: poppedController, preAnimation: { Void in self.rightController = newRightController }, postAnimation: { Void in self.leftController = poppedController }, completion: { Void in dismissingController?.view.removeFromSuperview() dismissingController?.removeFromParentViewController() }) } internal func addControllerToStack(_ controller: UINavigationController?) { if let controller = controller { controllers.append(controller) } } @discardableResult internal func popLastController() -> UINavigationController? { return controllers.popLast() } } extension CascadeController: CascadeDividerDelegate { func divider(_ divider: CascadeDividerView, shouldTranslateToCenter center: CGPoint) -> Bool { // Only allow the divider to translate if the minimum view sizes are met on the left and right return center.x >= minimumViewSize && center.x <= view.frame.width-minimumViewSize } func divider(_ divider: CascadeDividerView, didTranslateToCenter center: CGPoint) { dividerViewPositionConstraint.constant = center.x } } // MARK: - Styling extension CascadeController { func setupStyling() { leftViewContainer.backgroundColor = .white rightViewContainer.backgroundColor = .white dividerViewWidthConstraint.constant = UIScreen.main.onePx } }
0423828a4b8a253609d1b5c77a9bc399
35.2625
207
0.660634
false
false
false
false
lieonCX/Uber
refs/heads/master
UberRider/UberRider/View/SignIn/SignInViewController.swift
mit
1
// // SignInViewController.swift // UberRider // // Created by lieon on 2017/3/22. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit class SignInViewController: UIViewController { @IBOutlet weak var containerView: UIView! fileprivate var maxYContainerView: CGFloat = 0.0 @IBOutlet weak var verticalCons: NSLayoutConstraint! fileprivate var originalTopDistance: CGFloat = 0 @IBOutlet fileprivate weak var emailTextField: UITextField! @IBOutlet fileprivate weak var passwordTextField: UITextField! fileprivate var signinVM: AuthViewModel = AuthViewModel() @IBAction func loginAction(_ sender: Any) { if let email = emailTextField.text, let password = passwordTextField.text, email.isValidEmail() { signinVM.login(with: email, password: password) { [unowned self] message in if let message = message, !message.isEmpty { self.show(title: "Problem in Authentication", message: message) } else { self.emailTextField.text = "" self.passwordTextField.text = "" RiderViewModel.riderAccount = email self.showRiderVC() } } } else { self.show(title: "Email or Password required", message: "Please enter correct email or password in textfield") } } @IBAction func signUpAction(_ sender: Any) { if let email = emailTextField.text, let password = passwordTextField.text, email.isValidEmail() { signinVM.signup(with: email, password: password) { [unowned self] message in if let message = message, !message.isEmpty { self.show(title: "Problem in Authentication", message: message) } else { self.emailTextField.text = "" self.passwordTextField.text = "" RiderViewModel.riderAccount = email self.showRiderVC() } } } else { return self.show(title: "Email or Password required", message: "Please enter email or password in textfield") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) originalTopDistance = verticalCons.constant maxYContainerView = UIScreen.main.bounds.height - self.containerView.frame.maxY NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShowAction), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHideAction), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) verticalCons.constant = originalTopDistance NotificationCenter.default.removeObserver(self) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } } extension SignInViewController { static private var distance: CGFloat = 0 @objc fileprivate func keyboardWillShowAction(noti: Notification) { guard let userInfo = noti.userInfo, let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect else { return } let keyboardHeight = keyboardSize.height UIView.animate(withDuration: 0.25) { self.verticalCons.constant = self.originalTopDistance self.verticalCons.constant = self.originalTopDistance - (keyboardHeight - self.maxYContainerView) self.view.layoutIfNeeded() } } @objc fileprivate func keyboardWillHideAction() { UIView.animate(withDuration: 0.25) { self.verticalCons.constant = self.originalTopDistance self.view.layoutIfNeeded() } } fileprivate func showRiderVC() { self.performSegue(withIdentifier: "RiderHome", sender: nil) } }
b66b5e69d35f28e741fdb34276b0bc75
40.918367
161
0.647517
false
false
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/UI/MaterialFloatingSpinner.swift
apache-2.0
1
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_ShadowLayer_ShadowLayer // swiftlint:disable line_length import third_party_objective_c_material_components_ios_components_ActivityIndicator_ActivityIndicator // swiftlint:enable line_length /// A circular spinner contained in a shadowed, circular view. Best placed on top of cells or views /// to indicate loading after user interaction. class MaterialFloatingSpinner: UIView { enum Metrics { static let spinnerDimension: CGFloat = 32.0 static let spinnerPadding: CGFloat = 6.0 static let spinnerBackgroundDimenion = Metrics.spinnerDimension + Metrics.spinnerPadding } // MARK: - Properties override var intrinsicContentSize: CGSize { return CGSize(width: Metrics.spinnerBackgroundDimenion, height: Metrics.spinnerBackgroundDimenion) } /// The mode of the spinner. var indicatorMode: MDCActivityIndicatorMode { set { spinner.indicatorMode = newValue } get { return spinner.indicatorMode } } /// The progress for the spinner, when in determinate mode. The range is 0.0 to 1.0. var progress: Float { set { spinner.progress = newValue } get { return spinner.progress } } let spinner = MDCActivityIndicator() private let spinnerBackground = ShadowedView() // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } func startAnimating() { self.spinner.startAnimating() self.spinnerBackground.alpha = 1 } func stopAnimating() { self.spinnerBackground.alpha = 0 self.spinner.stopAnimating() } // MARK: - Private private func configureView() { addSubview(spinnerBackground) spinnerBackground.backgroundColor = .white spinnerBackground.translatesAutoresizingMaskIntoConstraints = false spinnerBackground.widthAnchor.constraint( equalToConstant: Metrics.spinnerBackgroundDimenion).isActive = true spinnerBackground.heightAnchor.constraint( equalToConstant: Metrics.spinnerBackgroundDimenion).isActive = true spinnerBackground.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true spinnerBackground.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true spinnerBackground.layer.cornerRadius = 19.0 spinnerBackground.setElevation(points: ShadowElevation.refresh.rawValue) spinnerBackground.alpha = 0 // Hidden by default. spinnerBackground.addSubview(spinner) spinner.indicatorMode = .indeterminate spinner.translatesAutoresizingMaskIntoConstraints = false spinner.widthAnchor.constraint(equalToConstant: Metrics.spinnerDimension).isActive = true spinner.heightAnchor.constraint(equalToConstant: Metrics.spinnerDimension).isActive = true spinner.centerXAnchor.constraint(equalTo: spinnerBackground.centerXAnchor).isActive = true spinner.centerYAnchor.constraint(equalTo: spinnerBackground.centerYAnchor).isActive = true } }
0207e4292e117f54c84047847a097ada
32.366071
101
0.746588
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/UIViewController+Push.swift
mit
1
import Foundation extension UIViewController { @objc(wmf_pushViewController:animated:) func push(_ viewController: UIViewController, animated: Bool = true) { if let navigationController = navigationController { navigationController.pushViewController(viewController, animated: true) } else if let presentingViewController = presentingViewController { presentingViewController.dismiss(animated: true) { presentingViewController.push(viewController, animated: animated) } } else if let parent = parent { parent.push(viewController, animated: animated) } else if let navigationController = self as? UINavigationController { navigationController.pushViewController(viewController, animated: animated) } } }
338f66ddaa76386190a1f831dfca7665
45.222222
87
0.698317
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/Components/AssetPieChartView/PieChartData+Conveniences.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Charts extension PieChartData { public convenience init(with values: [AssetPieChart.Value.Interaction]) { let values = values.map { AssetPieChart.Value.Presentation(value: $0) } let entries = values.map { PieChartDataEntry(value: $0.percentage.doubleValue, label: $0.debugDescription) } let set = PieChartDataSet(entries: entries, label: "") set.drawIconsEnabled = false set.drawValuesEnabled = false set.selectionShift = 0 set.sliceSpace = 3 set.colors = values.map(\.color) self.init(dataSet: set) } /// Returns an `empty` grayish pie chart data public static var empty: PieChartData { let set = PieChartDataSet(entries: [PieChartDataEntry(value: 100)], label: "") set.drawIconsEnabled = false set.drawValuesEnabled = false set.selectionShift = 0 set.colors = [Color.clear] return PieChartData(dataSet: set) } }
2645fa12e3c96f45f1231fef43a079a9
37.037037
116
0.661149
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
refs/heads/master
PerchReadyApp/apps/Perch/iphone/native/Perch/DataSources/AlertHistoryDataManager.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** Class for handling backend Worklight queries for data about all the notifications that have been generated for a given asset. */ public class AlertHistoryDataManager: NSObject { let currentUser = CurrentUser.sharedInstance var alerts: [Alert] = [] var callback: ((Bool)->())! var lastLoadedAlertHistory = "" public class var sharedInstance: AlertHistoryDataManager { struct Singleton { static let instance = AlertHistoryDataManager() } return Singleton.instance } /** Method to kick off worklight call to grab all alert history data - parameter callback: method to call when complete */ public func getAlertHistory(callback: ((Bool)->())!) { self.callback = callback let adapterName = "PerchAdapter" let procedureName = "getAllNotifications" let caller = WLProcedureCaller(adapterName: adapterName, procedureName: procedureName) var params: [String] // if let to get currDevId if let currDevId = CurrentSensorDataManager.sharedInstance.lastSelectedAsset { self.lastLoadedAlertHistory = currDevId params = [currentUser.userPin, currDevId] } else { params = [currentUser.userPin, ""] } caller.invokeWithResponse(self, params: params) } /** Method to parse json dictionary received from backend - parameter worklightResponseJson: json dictionary - returns: an array of SensorData objects */ func parseAlertHistoryResponse(worklightResponseJson: NSDictionary) -> [Alert] { var alertArray: [Alert] = [] if let serverAlerts = worklightResponseJson["result"] as? NSArray { for alert in serverAlerts { if let alertDictionary = alert as? NSDictionary { var alertObject: Alert! // This auto parsing into the object's properties is done through the JsonObject library alertObject = Alert(dictionary: alertDictionary, shouldValidate: false) // Since our timestamp info was not passed in a human readable format, we need to call this method to set the format alertObject.computeOptionalProperties() alertArray.append(alertObject) } } } return alertArray } } extension AlertHistoryDataManager: WLDataDelegate { /** Delgate method for WorkLight. Called when connection and return is successful - parameter response: Response from WorkLight */ public func onSuccess(response: WLResponse!) { MQALogger.log("Alert History Fetch Success Response: \(response.responseText)", withLevel: MQALogLevelInfo) let responseJson = response.getResponseJson() as NSDictionary alerts = parseAlertHistoryResponse(responseJson) callback(true) } /** Delgate method for WorkLight. Called when connection or return is unsuccessful - parameter response: Response from WorkLight */ public func onFailure(response: WLFailResponse!) { MQALogger.log("Alert History Fetch Failure Response: \(response.responseText)", withLevel: MQALogLevelInfo) if (response.errorCode.rawValue == 0) && (response.errorMsg != nil) { MQALogger.log("Response Failure with error: \(response.errorMsg)", withLevel: MQALogLevelInfo) } callback(false) } /** Delgate method for WorkLight. Task to do before executing a call. */ public func onPreExecute() { } /** Delgate method for WorkLight. Task to do after executing a call. */ public func onPostExecute() { } }
4aacf41acb75641762ec02a88bac2a15
32.965812
136
0.635128
false
false
false
false
zjjzmw1/SwiftCodeFragments
refs/heads/master
SwiftCodeFragments/Frameworks/MRPullToRefreshLoadMore/MRPullToRefreshLoadMore.swift
mit
2
import UIKit @objc public protocol MRPullToRefreshLoadMoreDelegate { func viewShouldRefresh(scrollView:UIScrollView) func viewShouldLoadMore(scrollView:UIScrollView) } public class MRPullToRefreshLoadMore:NSObject { public var scrollView:UIScrollView? public var pullToRefreshLoadMoreDelegate:MRPullToRefreshLoadMoreDelegate? public var enabled:Bool = true public var startingContentInset:UIEdgeInsets? public var pullToRefreshViewState:ViewState = ViewState.Normal public var loadMoreViewState:ViewState = ViewState.Normal public var arrowImage: CALayer? public var activityView: UIActivityIndicatorView? public var indicatorPullToRefresh = IndicatorView() public var indicatorLoadMore = IndicatorView() public var indicatorTintColor: UIColor? { didSet { indicatorLoadMore.indicatorTintColor = (indicatorTintColor ?? UIColor.red) indicatorPullToRefresh.indicatorTintColor = (indicatorTintColor ?? UIColor.red) } } var indicatorSize: CGSize = CGSize.init(width: 30.0, height: 30.0) public var textColor:UIColor = UIColor.red public enum ViewState { case Normal case LoadingHorizontal case LoadingVertical case ReadyHorizontal case ReadyVertical } public enum Drag { case Left case Top case Right case Bottom case None } public func initWithScrollView(scrollView:UIScrollView) { scrollView.addSubview(indicatorPullToRefresh) scrollView.addSubview(indicatorLoadMore) self.scrollView = scrollView scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) startingContentInset = scrollView.contentInset //print(startingContentInset) self.enabled = true setPullState(state: ViewState.Normal) setLoadMoreState(state: ViewState.Normal) } public func setLoadMoreState(state:ViewState) { loadMoreViewState = state switch (state) { case ViewState.ReadyVertical, ViewState.ReadyHorizontal: scrollView!.contentInset = self.startingContentInset! indicatorLoadMore.setAnimating(animating: false) case ViewState.Normal: indicatorLoadMore.setAnimating(animating: false) UIView.animate(withDuration: 0.2, animations: { self.scrollView!.contentInset = self.startingContentInset! }) case ViewState.LoadingVertical: indicatorLoadMore.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(0.0, 0.0, 60.0, 0.0) case ViewState.LoadingHorizontal: indicatorLoadMore.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 60.0) } } public func setPullState(state:ViewState) { pullToRefreshViewState = state switch (state) { case ViewState.ReadyHorizontal, ViewState.ReadyVertical: scrollView!.contentInset = self.startingContentInset! indicatorPullToRefresh.setAnimating(animating: false) case ViewState.Normal: indicatorPullToRefresh.setAnimating(animating: false) UIView.animate(withDuration: 0.2, animations: { self.scrollView!.contentInset = self.startingContentInset! }) case ViewState.LoadingHorizontal: indicatorPullToRefresh.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(0.0, 60.0, 0.0, 0.0) case ViewState.LoadingVertical: indicatorPullToRefresh.setAnimating(animating: true) scrollView!.contentInset = UIEdgeInsetsMake(60.0, 0.0, 0.0, 0.0) } } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { //} //override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { switch (keyPath) { case .some("contentOffset"): if (enabled) { // HORIZONTAL SCROLL let diff_x_end = scrollView!.contentOffset.x + scrollView!.bounds.width - scrollView!.contentSize.width let diff_x_start = 0 - scrollView!.contentOffset.x let diff_y_end = scrollView!.contentOffset.y + scrollView!.bounds.height - scrollView!.contentSize.height let diff_y_start = 0 - scrollView!.contentOffset.y var drag:Drag = .None // pull to refresh if diff_x_start > 0.0 { drag = .Left } else if diff_y_start > 0.0 { drag = .Top } else if diff_x_end > 0.0 { drag = .Right } else if diff_y_end > 0.0 { drag = .Bottom } switch(drag) { case .Top: indicatorPullToRefresh.frame = CGRect.init(x: scrollView!.bounds.width/2 - indicatorSize.width/2, y: -scrollView!.bounds.origin.y - 45 + scrollView!.contentOffset.y, width: indicatorSize.width, height: indicatorSize.height) case .Left: indicatorPullToRefresh.frame = CGRect.init(x: -45, y: scrollView!.bounds.height/2-15, width: indicatorSize.width, height: indicatorSize.height) case .Bottom: //indicatorLoadMore.frame = CGRectMake(scrollView!.bounds.width/2 - indicatorSize.width/2, 15 + scrollView!.contentSize.height, indicatorSize.width, indicatorSize.height) indicatorLoadMore.frame = CGRect.init(x: scrollView!.bounds.width/2 - indicatorSize.width/2, y: 15 + scrollView!.contentSize.height, width: indicatorSize.width, height: indicatorSize.height) case .Right: //indicatorLoadMore.frame = CGRectMake(scrollView!.contentSize.width + 15, scrollView!.bounds.height/2 - 15, indicatorSize.width, indicatorSize.height) indicatorLoadMore.frame = CGRect.init(x: scrollView!.contentSize.width + 15, y: scrollView!.bounds.height/2-15, width: indicatorSize.width, height: indicatorSize.height) default: break } if (scrollView!.isDragging) { switch(drag) { case .Top: switch(pullToRefreshViewState) { case ViewState.ReadyVertical: indicatorPullToRefresh.interactiveProgress = diff_y_start / 130.0 if (diff_y_start < 65.0) { setPullState(state: ViewState.Normal) } case ViewState.Normal: indicatorPullToRefresh.interactiveProgress = diff_y_start / 130.0 if (diff_y_start > 65.0) { setPullState(state: ViewState.ReadyVertical) } default: break } case .Left: switch(pullToRefreshViewState) { case ViewState.ReadyHorizontal: indicatorPullToRefresh.interactiveProgress = diff_x_start / 130.0 if (diff_x_start < 65.0) { setPullState(state: ViewState.Normal) } case ViewState.Normal: indicatorPullToRefresh.interactiveProgress = diff_x_start / 130.0 if (diff_x_start > 65.0) { setPullState(state: ViewState.ReadyHorizontal) } default: break } case .Bottom: switch(loadMoreViewState) { case ViewState.ReadyVertical: indicatorLoadMore.interactiveProgress = diff_y_end / 130.0 if (diff_y_end < 65.0) { setLoadMoreState(state: ViewState.Normal) } case ViewState.Normal: indicatorLoadMore.interactiveProgress = diff_y_end / 130.0 if (diff_y_end > 65.0) { setLoadMoreState(state: ViewState.ReadyVertical) } default: break } case .Right: switch(loadMoreViewState) { case ViewState.ReadyHorizontal: indicatorLoadMore.interactiveProgress = diff_x_end / 130.0 if (diff_x_end < 65.0) { setLoadMoreState(state: ViewState.Normal) } case ViewState.Normal: indicatorLoadMore.interactiveProgress = diff_x_end / 130.0 if (diff_x_end > 65.0) { setLoadMoreState(state: ViewState.ReadyHorizontal) } default: break } default: break } } else { // pull to refresh if (pullToRefreshViewState == ViewState.ReadyHorizontal || pullToRefreshViewState == ViewState.ReadyVertical) { UIView.animate(withDuration: 0.2, animations: { if self.pullToRefreshViewState == ViewState.ReadyHorizontal { self.setPullState(state: ViewState.LoadingHorizontal) } else { self.setPullState(state: ViewState.LoadingVertical) } }) if let pullToRefreshLoadMoreDelegate = pullToRefreshLoadMoreDelegate { pullToRefreshLoadMoreDelegate.viewShouldRefresh(scrollView: scrollView!) } } // load more if (loadMoreViewState == ViewState.ReadyHorizontal || loadMoreViewState == ViewState.ReadyVertical) { UIView.animate(withDuration: 0.2, animations: { if self.loadMoreViewState == ViewState.ReadyHorizontal { self.setLoadMoreState(state: ViewState.LoadingHorizontal) } else { self.setLoadMoreState(state: ViewState.LoadingVertical) } }) if let pullToRefreshLoadMoreDelegate = pullToRefreshLoadMoreDelegate { pullToRefreshLoadMoreDelegate.viewShouldLoadMore(scrollView: scrollView!) } } } //print(loadMoreViewState) } default: break } } } public class MRTableView:UITableView { public var pullToRefresh:MRPullToRefreshLoadMore = MRPullToRefreshLoadMore() required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) pullToRefresh.initWithScrollView(scrollView: self) } override public init(frame: CGRect, style: UITableViewStyle) { super.init(frame:frame, style:style) pullToRefresh.initWithScrollView(scrollView: self) } } public class MRCollectionView:UICollectionView { public var pullToRefresh:MRPullToRefreshLoadMore = MRPullToRefreshLoadMore() required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) pullToRefresh.initWithScrollView(scrollView: self) } override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame:frame, collectionViewLayout:layout) pullToRefresh.initWithScrollView(scrollView: self) } }
e5b23f66f27eedc6c93cc03e813825d8
44.37234
243
0.549433
false
false
false
false
sayanee/ios-learning
refs/heads/master
Smashtag/Smashtag/TweetTableViewCell.swift
mit
1
// // TweetTableViewCell.swift // Smashtag // // Created by Sayanee Basu on 14/1/16. // Copyright © 2016 Sayanee Basu. All rights reserved. // import UIKit class TweetTableViewCell: UITableViewCell { var tweet: Tweet? { didSet { updateUI() } } @IBOutlet weak var tweetProfileImageView: UIImageView! @IBOutlet weak var tweetScreenNameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! func updateUI() { tweetTextLabel?.attributedText = nil tweetScreenNameLabel?.text = nil tweetProfileImageView?.image = nil // tweetCreatedLabel?.text = nil if let tweet = self.tweet { tweetTextLabel?.text = tweet.text if tweetTextLabel?.text != nil { for _ in tweet.media { tweetTextLabel.text! += " 📷" } } tweetScreenNameLabel?.text = "\(tweet.user)" if let profileImageURL = tweet.user.profileImageURL { if let imageData = NSData(contentsOfURL: profileImageURL) { // blocks main thread! tweetProfileImageView?.image = UIImage(data: imageData) } } // let formatter = NSDateFormatter() // if NSDate().timeIntervalSinceDate(tweet.created) > 24*60*60 { // formatter.dateStyle = NSDateFormatterStyle.ShortStyle // } else { // formatter.timeStyle = NSDateFormatterStyle.ShortStyle // } // // tweetCreatedLabel?.text = formatter.stringFromDate(tweet.created) } } }
5fc276250ae119392e5df9c668fb5ca6
29.607143
79
0.549592
false
false
false
false
andrebng/Food-Diary
refs/heads/master
Food Snap/View Controllers/New Meal View Controller/View Models/NewMealViewViewModel.swift
mit
1
// // NewMealViewViewModel.swift // Food Snap // // Created by Andre Nguyen on 9/21/17. // Copyright © 2017 Idiots. All rights reserved. // import UIKit enum ViewModelState { case isEmpty case isMissingValue case notEmpty } @available(iOS 11.0, *) class NewMealViewViewModel { // MARK: - Properties var name: String = "" { didSet { didUpdateName?(name) } } var calories: Float = 0 { didSet { caloriesAsString = String(format: "%.0f kcal", calories) } } var caloriesAsString: String = "" { didSet { didUpdateCaloriesString?(caloriesAsString) } } var fat: Float = 0 { didSet { fatAsString = String(format: "%.0f g", fat) } } var fatAsString: String = "" { didSet { didUpdateFatString?(fatAsString) } } // MARK: - var image: UIImage = UIImage() { didSet { performImageRecognition(image: image) } } // MARK: - Public Interface var didUpdateName: ((String) -> ())? var didUpdateCaloriesString: ((String) -> ())? var didUpdateFatString: ((String) -> ())? // MARK: - var queryingDidChange: ((Bool) -> ())? var didRecognizeImages: (([Meal]) -> ())? // MARK: - Private private lazy var mlManager = MLManager() private lazy var nutritionixAPI = NutritionixAPI() private var querying: Bool = false { didSet { queryingDidChange?(querying) } } // MARK - Public Methods func toMeal() -> Meal? { if (self.state() == .isEmpty || self.state() == .isMissingValue) { return nil } return Meal(name: name, calories: calories, fat: fat) } func state() -> ViewModelState { let hasNameValue = (name.isEmpty && name != "Name of Food / Dish") ? false : true let hasCaloriesValue = caloriesAsString.isEmpty ? false : true let hasFatValue = fatAsString.isEmpty ? false : true if (!hasNameValue && !hasCaloriesValue && !hasFatValue) { return .isEmpty } else if (hasNameValue && hasCaloriesValue && hasFatValue) { return .notEmpty } return .isMissingValue } // MARK - Helper Methods func performImageRecognition(image: UIImage?) { guard let image = image else { return } querying = true let prediction = mlManager.predictionForImage(image: image) if let meal = prediction { nutritionixAPI.nutritionInfo(foodName: meal) { [weak self] (meals, error) in if let error = error { print("Error forwarding meals (\(error)") } else { self?.querying = false if let meals = meals { self?.didRecognizeImages?(meals) } } } } } }
7805be4fa03cdf46737355c01eaac772
23.294574
89
0.513082
false
false
false
false
natestedman/PrettyOkayKit
refs/heads/master
PrettyOkayKit/WantEndpoint.swift
isc
1
// Copyright (c) 2016, Nate Stedman <nate@natestedman.com> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. import Endpoint import Foundation import Result // MARK: - Wanting /// An endpoint for wanting a product. internal struct WantEndpoint: CSRFTokenEndpointType { // MARK: - Initialization /** Initializes a want endpoint. - parameter identifier: The identifier of the product to want. */ init(username: String, identifier: ModelIdentifier, CSRFToken: String) { self.username = username self.identifier = identifier self.CSRFToken = CSRFToken } // MARK: - Data /// The username of the user wanting the product. let username: String /// The identifier of the product to want. let identifier: ModelIdentifier /// The CSRF token for the request. let CSRFToken: String } extension WantEndpoint: Encoding { var encoded: [String : AnyObject] { return ["product_id": identifier] } } extension WantEndpoint: BaseURLEndpointType, BodyProviderType, HeaderFieldsProviderType, MethodProviderType, RelativeURLStringProviderType { var method: Endpoint.Method { return .Post } var relativeURLString: String { return "users/\(username.pathEscaped)/goods" } } extension WantEndpoint: ProcessingType { func resultForInput(input: AnyObject) -> Result<String?, NSError> { return .Success( (input as? [String:AnyObject]) .flatMap({ $0["_links"] as? [String:AnyObject] }) .flatMap({ $0["self"] as? [String:AnyObject] }) .flatMap({ $0["href"] as? String }) .map({ $0.removeLeadingCharacter }) ) } } // MARK: - Unwanting /// An endpoint for unwanting a product. internal struct UnwantEndpoint: CSRFTokenEndpointType { // MARK: - Initialization /// Initializes an unwant endpoint /// /// - parameter goodDeletePath: The URL path to use. /// - parameter CSRFToken: The CSRF token to use. init(goodDeletePath: String, CSRFToken: String) { self.goodDeletePath = goodDeletePath self.CSRFToken = CSRFToken } // MARK: - Data /// The URL path to request. let goodDeletePath: String /// A CSRF token. let CSRFToken: String } extension UnwantEndpoint: BaseURLEndpointType, HeaderFieldsProviderType, MethodProviderType, RelativeURLStringProviderType { var method: Endpoint.Method { return .Delete } var relativeURLString: String { return goodDeletePath } var headerFields: [String : String] { return ["Csrf-Token": CSRFToken] } } extension UnwantEndpoint: ProcessingType { func resultForInput(input: AnyObject) -> Result<String?, NSError> { return .Success(nil) } } /// A protocol for endpoints that require a CSRF token. protocol CSRFTokenEndpointType { /// The CSRF token. var CSRFToken: String { get } } // MARK: - Encodable Endpoint Extension extension Encoding where Self: BodyProviderType, Self: HeaderFieldsProviderType, Self: CSRFTokenEndpointType { var body: BodyType? { return try? NSJSONSerialization.dataWithJSONObject(encoded, options: []) } var headerFields: [String: String] { return [ "Content-Type": "application/json;charset=UTF-8", "Csrf-Token": CSRFToken, "Origin": "https://verygoods.co", "X-Requested-With": "XMLHttpRequest", "Referer": "https://verygoods.co" ] } }
aaa18e7f3b40f8d834a88f0ecf1eca2d
27.986755
108
0.648846
false
false
false
false
anitaleung/codepath-tip-pal
refs/heads/master
tips/ViewController.swift
mit
2
// // ViewController.swift // tips // // Created by Anita on 12/4/15. // Copyright © 2015 Anita. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var beneathBillField: UITextField! let defaults = NSUserDefaults.standardUserDefaults() override func viewDidLoad() { super.viewDidLoad() tipControl.selectedSegmentIndex = 1 billField.text = defaults.stringForKey("lastAmount")! tipLabel.text = "$0.00" totalLabel.text = "$0.00" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) doCalculations() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Do calculations for total price func doCalculations() { let defaultTipPercent = defaults.stringForKey("defaultTip") var tipPercent = 20.0 if (defaultTipPercent != nil) { tipPercent = Double(defaultTipPercent!)! } var tipPercentages = [tipPercent - 2, tipPercent, tipPercent + 2] let tipPercentage = tipPercentages[tipControl.selectedSegmentIndex] / 100 for i in 0...2 { tipControl.setTitle(String(format: "%.f%%", tipPercentages[i]), forSegmentAtIndex: i) if (tipPercent == 0) { tipControl.setTitle("0%", forSegmentAtIndex: i) } } let billAmount = NSString(string: billField.text!).doubleValue let tip = abs(billAmount * tipPercentage) let total = billAmount + tip defaults.setObject(billField.text, forKey: "lastAmount") defaults.synchronize() tipLabel.text = "$\(tip)" totalLabel.text = "$\(total)" tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } @IBAction func onEditingChanged(sender: AnyObject) { doCalculations() } // Close keyboard when user taps elsewhere @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } // Animations }
d74041dcbdd2ec046ca7a0ee8e8af504
27.337209
97
0.613049
false
false
false
false
TheDarkCode/Example-Swift-Apps
refs/heads/master
Exercises and Basic Principles/seques-basics/seques-basics/ViewController.swift
mit
1
// // ViewController.swift // seques-basics // // Created by Mark Hamilton on 2/19/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func loadBlue(sender: AnyObject!) { // Use SENDER to Pass Any Data let sendString: String = "Just came from Yellow View!" performSegueWithIdentifier("goToBlue", sender: sendString) } @IBAction func loadRed(sender: AnyObject!) { performSegueWithIdentifier("goToRed", sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Do any work before view loads. // Other View controller has already been initialized, just not in view. if segue.identifier == "goToBlue" { if let blueVC = segue.destinationViewController as? BlueViewController { if let sentStr = sender as? String { blueVC.transferText = sentStr } } } } }
7bc21dd6f93597c0ee250ec122325cb8
23.66
84
0.559611
false
false
false
false
damicreabox/Git2Swift
refs/heads/master
Sources/Git2Swift/authentication/KeyAuthentication.swift
apache-2.0
1
// // KeyAuthentication.swift // Git2Swift // // Created by Damien Giron on 11/09/2016. // Copyright © 2016 Creabox. All rights reserved. // import Foundation import CLibgit2 public protocol SshKeyData { /// Find user name var username : String? { get } /// Find public key URL var publicKey : URL { get } /// Find private key URL var privateKey : URL { get } /// Key pass phrase (may be nil) var passphrase : String? { get } } public struct RawSshKeyData : SshKeyData { public let username : String? public let publicKey : URL public let privateKey : URL public let passphrase : String? public init(username : String?, publicKey : URL, privateKey : URL, passphrase : String? = nil) { self.username = username self.publicKey = publicKey self.privateKey = privateKey self.passphrase = passphrase } } /// Ssh key delegate public protocol SshKeyDelegate { /// Get ssh key data /// /// - parameter username: username /// - parameter url: url /// /// - returns: Password data func get(username: String?, url: URL?) -> SshKeyData } /// SSh authentication public class SshKeyHandler : AuthenticationHandler { /// Delegate to access SSH key private let sshKeyDelegate: SshKeyDelegate public init(sshKeyDelegate: SshKeyDelegate) { self.sshKeyDelegate = sshKeyDelegate } /// Authentication /// /// - parameter out: Git credential /// - parameter url: url /// - parameter username: username /// /// - returns: 0 on ok public func authenticate(out: UnsafeMutablePointer<UnsafeMutablePointer<git_cred>?>?, url: String?, username: String?) -> Int32 { // Find ssh key data let sshKeyData = sshKeyDelegate.get(username: username, url: url == nil ? nil : URL(string: url!)) // Public key let publicKey = sshKeyData.publicKey.path if (FileManager.default.fileExists(atPath: publicKey) == false) { return 1 } // Private key let privateKey = sshKeyData.privateKey.path if (FileManager.default.fileExists(atPath: privateKey) == false) { return 2 } // User name let optionalUsername = sshKeyData.username let optionalPassPhrase = sshKeyData.passphrase return git_cred_ssh_key_new(out, optionalUsername == nil ? "": optionalUsername!, publicKey, privateKey, optionalPassPhrase == nil ? "": optionalPassPhrase!) } }
68bf976dee21c3e2d11916df71c3b4b3
25.564815
106
0.560823
false
false
false
false
chenzhe555/core-ios-swift
refs/heads/master
core-ios-swift/AppDelegate.swift
mit
1
// // AppDelegate.swift // core-ios-swift // // Created by 陈哲#376811578@qq.com on 16/2/17. // Copyright © 2016年 陈哲是个好孩子. All rights reserved. // import UIKit import Alamofire typealias funcBlock = () -> String @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, BaseHttpServiceDelegate_s { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let dic1: NSMutableDictionary = ["key1":"1111","key2":"2222","key1":"333","key6": ["key1":"66","key2": "xxxx"]]; let dic2: NSMutableDictionary = ["key1":"1111","key2":"2222","key1":"333","key6": ["key1":"66","key2": "xxxx"]]; // BaseHttpEncryption.encrytionParameterMethod1(dic1, andKeyArray: MCHttpEncryption.setParametersArray()); do{ try BaseHttpEncryption_s.encrytionParameterMethod1(dic2, keyArray: MCHttpEncryption_s.setParametersArray()); } catch BaseHttpErrorType_s.NotOverrideMethod_setParamater { print("------------------"); } catch { } // Alamofire.request(.GET, "http://www.test.com").responseJSON { (response) -> Void in // print("回来了呢\(response.result)"); // }; // // // // // Alamofire.request(.GET, "http://localhost/launchadconfig/getimg", parameters: ["account": "chenzhe","password": "111"], encoding: .URL, headers: ["Content-Type": "application/json"]).responseJSON { (response) -> Void in // print(response.result); // }; // Alamofire.request(.GET, "http://localhost/launchadconfig/getimg").responseJSON { (response) -> Void in // print(response.result.value); // }"core-ios-swift/Framework_swift/Service/*.{h,swift}" // MCLog("陈哲是个好孩子"); let service = MCHttpService(); service.delegate = self; // service.login("chenzhe", password: "111", requsetObj: HttpAppendParamaters_s.init(needToken: true, alertType: MCHttpAlertType_s.MCHttpAlertTypeNone_s)); service.login("chenzhe", password: "111", condition: BaseHttpAppendCondition_s()); let v1: UIViewController = ViewController(); let v2: UIViewController = ViewController(); let v3: UIViewController = ViewController(); let v4: UIViewController = ViewController(); let nav1: UINavigationController = UINavigationController(rootViewController: v1); let nav2: UINavigationController = UINavigationController(rootViewController: v2); let nav3: UINavigationController = UINavigationController(rootViewController: v3); let nav4: UINavigationController = UINavigationController(rootViewController: v4); let tabbar: BaseTabbar_s = BaseTabbar_s(); tabbar.setDataArray(["1111","2222","333","4"], normalArray: [UIImage(named: "icon_my_normal")!,UIImage(named: "icon_allGoods_normal")!,UIImage(named: "icon_home_normal")!,UIImage(named: "icon_shopCart_normal")!], selectedArray: [UIImage(named: "icon_my_selected")!,UIImage(named: "icon_allGoods_selected")!,UIImage(named: "icon_home_selected")!,UIImage(named: "icon_shopCart_selected")!]); tabbar.viewControllers = [nav1,nav2,nav3,nav4]; tabbar.createTabbar(); self.window?.rootViewController = tabbar; return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func requesetSuccess(response: BaseHttpResponse_s) { print("打印出来是---\(response.object)"); } func requestFail(response: BaseHttpResponse_s) { print("失败打印出来是---\(response.object)"); } }
c870c92416a7c5e46cefac10cbbfff2a
46.025862
397
0.672411
false
false
false
false
shinobicontrols/iOS8-LevellingUp
refs/heads/master
LevellingUp/NotificationAuthorisationViewController.swift
apache-2.0
1
// // Copyright 2015 Scott Logic // // 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 UIKit class NotificationAuthorisationViewController: UIViewController { let red = UIColor.redColor() let green = UIColor.greenColor() @IBOutlet weak var badgesLabel: UILabel! @IBOutlet weak var soundsLabel: UILabel! @IBOutlet weak var alertsLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() title = "Notification Authorisation" // Register to get updates on notification authorisation status NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateLabelsWithCurrentStatus", name: userNotificationSettingsKey, object: nil) // Do any additional setup after loading the view. updateLabelsWithCurrentStatus() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK:- Actions @IBAction func handleRequestAction(sender: AnyObject) { let requestedTypes: UIUserNotificationType = .Alert | .Sound | .Badge requestNotificationsForTypes(requestedTypes) } @IBAction func handleJumpToSettings(sender: AnyObject) { let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString) UIApplication.sharedApplication().openURL(settingsUrl!) } // MARK:- Utils func updateLabelsWithCurrentStatus() { let types = UIApplication.sharedApplication().currentUserNotificationSettings().types badgesLabel.backgroundColor = (types & UIUserNotificationType.Badge == nil) ? red : green alertsLabel.backgroundColor = (types & UIUserNotificationType.Alert == nil) ? red : green soundsLabel.backgroundColor = (types & UIUserNotificationType.Sound == nil) ? red : green } private func requestNotificationsForTypes(types: UIUserNotificationType) { let settingsRequest = UIUserNotificationSettings(forTypes: types, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settingsRequest) } }
5dd020703ca7059077a5376ea1c61213
33.438356
93
0.743835
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Models/Subscription/Subscription.swift
mit
1
// // Subscription.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/9/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON enum SubscriptionType: String, Equatable { case directMessage = "d" case channel = "c" case group = "p" } enum SubscriptionNotificationsStatus: String, CaseIterable { case `default` case nothing case all case mentions } enum SubscriptionNotificationsAudioValue: String, CaseIterable { case none case `default` case beep case chelle case ding case droplet case highbell case seasons } typealias RoomType = SubscriptionType final class Subscription: BaseModel { @objc dynamic var auth: Auth? @objc internal dynamic var privateType = SubscriptionType.channel.rawValue var type: SubscriptionType { get { return SubscriptionType(rawValue: privateType) ?? SubscriptionType.group } set { privateType = newValue.rawValue } } @objc dynamic var rid = "" @objc dynamic var prid = "" // Name of the subscription @objc dynamic var name = "" // Full name of the user, in the case of // using the full user name setting // Setting: UI_Use_Real_Name @objc dynamic var fname = "" @objc dynamic var unread = 0 @objc dynamic var userMentions = 0 @objc dynamic var groupMentions = 0 @objc dynamic var open = false @objc dynamic var alert = false @objc dynamic var favorite = false @objc dynamic var createdAt: Date? @objc dynamic var lastSeen: Date? @objc dynamic var usersCount = 0 @objc dynamic var roomTopic: String? @objc dynamic var roomDescription: String? @objc dynamic var roomAnnouncement: String? @objc dynamic var roomReadOnly = false @objc dynamic var roomUpdatedAt: Date? @objc dynamic var roomLastMessage: Message? @objc dynamic var roomLastMessageText: String? @objc dynamic var roomLastMessageDate: Date? @objc dynamic var roomBroadcast = false let roomMuted = List<String>() @objc dynamic var roomOwnerId: String? @objc dynamic var otherUserId: String? @objc dynamic var disableNotifications = false @objc dynamic var hideUnreadStatus = false @objc dynamic var desktopNotificationDuration = 0 @objc internal dynamic var privateDesktopNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateEmailNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateMobilePushNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateAudioNotifications = SubscriptionNotificationsStatus.default.rawValue @objc internal dynamic var privateAudioNotificationsValue = SubscriptionNotificationsAudioValue.default.rawValue var desktopNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateDesktopNotifications) ?? .default } set { privateDesktopNotifications = newValue.rawValue } } var emailNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateEmailNotifications) ?? .default } set { privateEmailNotifications = newValue.rawValue } } var mobilePushNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateMobilePushNotifications) ?? .default } set { privateMobilePushNotifications = newValue.rawValue } } var audioNotifications: SubscriptionNotificationsStatus { get { return SubscriptionNotificationsStatus(rawValue: privateAudioNotifications) ?? .default } set { privateAudioNotifications = newValue.rawValue } } var audioNotificationValue: SubscriptionNotificationsAudioValue { get { return SubscriptionNotificationsAudioValue(rawValue: privateAudioNotificationsValue) ?? .default } set { privateAudioNotificationsValue = newValue.rawValue } } let usersRoles = List<RoomRoles>() // MARK: Internal @objc dynamic var privateOtherUserStatus: String? var otherUserStatus: UserStatus? { if let privateOtherUserStatus = privateOtherUserStatus { return UserStatus(rawValue: privateOtherUserStatus) } else { return nil } } var messages: Results<Message>? { return Realm.current?.objects(Message.self).filter("rid == '\(rid)'") } var isDiscussion: Bool { return !prid.isEmpty } static func find(rid: String, realm: Realm? = Realm.current) -> Subscription? { return realm?.objects(Subscription.self).filter("rid == '\(rid)'").first } static func find(name: String, realm: Realm? = Realm.current) -> Subscription? { return realm?.objects(Subscription.self).filter("name == '\(name)'").first } } final class RoomRoles: Object { @objc dynamic var user: User? var roles = List<String>() } // MARK: Avatar extension Subscription { static func avatarURL(for name: String, auth: Auth? = nil) -> URL? { guard let auth = auth ?? AuthManager.isAuthenticated(), let baseURL = auth.baseURL(), let userId = auth.userId, let token = auth.token, let encodedName = name.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return nil } return URL(string: "\(baseURL)/avatar/%22\(encodedName)?format=jpeg&rc_uid=\(userId)&rc_token=\(token)") } } // MARK: Display Name extension Subscription { func displayName() -> String { guard let settings = AuthSettingsManager.settings else { return name } if type != .directMessage { if !prid.isEmpty { return !fname.isEmpty ? fname : name } return settings.allowSpecialCharsOnRoomNames && !fname.isEmpty ? fname : name } return settings.useUserRealName && !fname.isEmpty ? fname : name } } // MARK: Unmanaged Object extension Subscription: UnmanagedConvertible { typealias UnmanagedType = UnmanagedSubscription var unmanaged: UnmanagedSubscription? { return UnmanagedSubscription(self) } }
756cf281ae372f482132a63673879dbb
31.426396
116
0.694114
false
false
false
false
enisinanaj/1-and-1.workouts
refs/heads/master
1and1.workout/Controllers/CounterViewController.swift
mit
1
// // CounterViewController.swift // 1and1.workout // // Created by Eni Sinanaj on 17/08/2017. // Copyright © 2017 Eni Sinanaj. All rights reserved. // import UIKit import AVFoundation import AudioToolbox class CounterViewController: UIViewController { var parentController: MainPageViewController? var minutes = 0 var seconds = 0 var timer: Timer! var sets: Int = 1 var timeKeeper: Double = 0.0 var startSeconds: Double = 0.0 var sectionSeconds: Double = 0.0 var differenceInSecconds: Double = 0.0 var restMinuteConsumed: Bool = false var player: AVAudioPlayer? @IBOutlet weak var counterBaseView: UIView! @IBOutlet weak var restLabel: UILabel! @IBOutlet weak var setLabel: UILabel! @IBOutlet weak var secondHand: UILabel! @IBOutlet weak var minuteHand: UILabel! var running: Bool! @IBOutlet weak var baseWindowView: UIView! override func viewDidLoad() { super.viewDidLoad() baseWindowView.layer.cornerRadius = 5 // baseWindowView.frame.origin.y = baseWindowView.frame.origin.y + 10 counterBaseView.layer.shadowColor = UIColor.black.cgColor counterBaseView.layer.shadowOffset = counterBaseView.frame.size counterBaseView.layer.shadowRadius = 100 counterBaseView.layer.shadowPath = UIBezierPath(rect: counterBaseView.bounds).cgPath counterBaseView.layer.shouldRasterize = true restLabel.isHidden = true } @IBAction func restartNewSet(_ sender: Any) { if running { return } sets = sets + 1 setLabel.text = "Set " + String(sets) restLabel.isHidden = true restMinuteConsumed = false self.timeKeeper = 0 startTime(self) } @IBAction func stopTimerAction(_ sender: Any) { let wasRunning = running parentController?.completeExercise(wasRunning!) stopTime() self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func startTime(_ sender: AnyObject) { running = true self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) self.timeKeeper = 0 self.startSeconds = CACurrentMediaTime() self.differenceInSecconds = 0.0 self.resetTimerCounters() } func stopTime() { timer.invalidate() running = false restLabel.isHidden = true self.resetTimerCounters() sectionSeconds = (parentController?.exercise?.duration)! * Double(sets) } func resetTimerCounters() { minutes = 0 seconds = 0 minuteHand.text = "00" secondHand.text = "00" } func startRestMinute() { stopTime() restMinuteConsumed = true startTime(self) restLabel.isHidden = false } @objc func update() { if parentController?.exercise?.duration == self.timeKeeper && !self.restMinuteConsumed { playSound() startRestMinute() } else if parentController?.exercise?.restDuration == self.timeKeeper && self.restMinuteConsumed { stopTime() } else { self.timeKeeper += 1 incrementSeconds() minuteHand.text = getAsString(timePart: minutes) secondHand.text = getAsString(timePart: seconds) } } func playSound() { let url = Bundle.main.url(forResource: "doneBell.mp3", withExtension: nil)! do { player = try AVAudioPlayer(contentsOf: url) guard let player = player else {return} player.prepareToPlay() player.play(); } catch let error as NSError { print(error.description) } } func getIntervalFromStartTime() -> Double { return CACurrentMediaTime() - startSeconds } func incrementMinutes() { if (minutes == 59) { minutes = 0 if (seconds == 59) { seconds = 0 resetTimerCounters() } } else { minutes += 1 } } func incrementSeconds() { if (seconds == 59) { seconds = 0 incrementMinutes() } else { seconds += 1 } } func reloadTimer(notification: Notification) { differenceInSecconds = CACurrentMediaTime() - self.startSeconds let divisorForMinutes = differenceInSecconds.truncatingRemainder(dividingBy: (60.0 * 60.0)) let minutesD = floor(divisorForMinutes / 60.0) let divisorForSeconds = divisorForMinutes.truncatingRemainder(dividingBy: 60.0) let secondsD = ceil(divisorForSeconds) if self.startSeconds > 0.0 { self.seconds = Int(secondsD) self.minutes = minutesD > 1 ? Int(minutesD) : self.minutes } } func secondsToTimeString(_ seconds: NSInteger) -> (minutes: NSInteger, seconds: NSInteger) { let minutes = seconds / 60 let seconds = seconds % 60 return (minutes: minutes, seconds: seconds) } func getAsString(timePart: NSInteger) -> String { if (timePart == 0) { return "00" } else if (timePart > 0 && timePart < 10) { return "0" + String(timePart) } else { return String(timePart) } } }
1b187801c1df7d9f9d2c19e5fa59b928
27.688442
136
0.583815
false
false
false
false
StachkaConf/ios-app
refs/heads/develop
StachkaIOS/StachkaIOS/Classes/Helpers/FilterFactory/FilterFactoryImplementation.swift
mit
1
// // FilterFactoryImplementation.swift // StachkaIOS // // Created by m.rakhmanov on 31.03.17. // Copyright © 2017 m.rakhmanov. All rights reserved. // import Foundation class FilterFactoryImplementation: FilterFactory { private var categoryNames = ["Разработка", "Digital-маркетинг", "Бизнес", "Образование и карьера"] private var placeNames = ["БОЛЬШОЙ ЗАЛ", "КИНОБАР", "АРХИВ", "ПРЕСС-ЦЕНТР", "ФОЙЕ ОПЦ", "КИНОЗАЛ МУЗЕЯ", "ОКТЯБРЬСКИЙ", "ЗАЛ МУЗЕЯ №16", "ФОЙЕ МУЗЕЯ", "СОВЕТСКАЯ ШКОЛА"] private var sectionNames = ["Разработка": ["Информационная безопасность", "Менеджмент", "HighLoad", "Виртуальная реальность", "DevOps", "FrontEnd", "BackEnd", "Мобильная", "Database", "Тестирование", "Управление требованиями", "Машинное обучение"], "Digital-маркетинг": ["Digital", "SEO", "Web-аналитика", "Графический продакшен", "Лидогенерация"], "Бизнес": ["Бизнес-инструменты", "Электронная коммерция"], "Образование и карьера": ["Подготовка ИТ профессионалов", "Студентам", "Управленцам, HR-ам", "IT-сообщества"]] func createFilters() -> [Filter] { return [createAllPlacesFilter()] + createCategoryFilters() } private func createCategoryFilters() -> [CategoryFilter] { return categoryNames.map { let categotyFilter = CategoryFilter() categotyFilter.title = $0 categotyFilter.selected = true let objects = createSectionFilter(withCategory: $0) // FIXME: почему-то синтаксис с append(objectsIn:) не заработал objects.forEach { categotyFilter.sectionFilters.append($0) } return categotyFilter } } private func createAllPlacesFilter() -> AllPlacesFilter { let allPlacesFilter = AllPlacesFilter() allPlacesFilter.title = "Залы" allPlacesFilter.selected = true placeNames.forEach { let placeFilter = PlaceFilter() placeFilter.title = $0 placeFilter.selected = true allPlacesFilter.placeFilters.append(placeFilter) } return allPlacesFilter } private func createSectionFilter(withCategory category: String) -> [SectionFilter] { return sectionNames[category]?.map { let sectionFilter = SectionFilter() sectionFilter.selected = true sectionFilter.title = $0 return sectionFilter } ?? [] } }
03efbf453bafb995a946747eba5ce85e
40.333333
142
0.580279
false
false
false
false